如何从JavaScript发送一个变量来使用AJAX PHP脚本变量、脚本、JavaScript、PHP

2023-09-10 20:19:42 作者:浓酒烈

有关我的项目,我需要做到以下几点:

For my project I need to do the following:

用户presses他的鼠标在画布(HTML页) JavaScript函数保存了已经pressed 的点的坐标 在发送该信息到一个PHP脚本 在PHP脚本添加这些数据到MySQL数据库 在其他坐标投入JSON和发送到回psented相同的画布上的客户端和$ P $ User presses his Mouse on the canvas (html page) JavaScript function saves the coordinates of the points that have been pressed Send this info to a PHP script PHP script adds this data to MySQL database Other coordinates are put into JSON and sent to back to the client and presented on the same canvas

现在,我已经研究过第3步的问题(这是一件好事,我不知道该怎么做)。有不同的方式,我选择了这两个:

Now, I have looked into the problem of step 3 (which is something I don't know how to do). There are different ways, I have selected these two:

使用Ajax HtmlRequest (回答3) Using Ajax HtmlRequest (answer 3)

这将是我的情况选择最佳的方法是什么?是否有尚未更好的/正确的方式做到这一点?

Which would be the best way to choose in my situation? Is there yet a better / right way to do it?

推荐答案

我不会说有必然是一个正确的方式做到这一点,但也有可以遵循一些好的想法。其中的一个想法是使用 HTTP REST动词:在使用 POST 为创造的操作和 GET 为读操作。鉴于这种情况,你应该做一个AJAX POST 请求到服务器,并通过 POST 参数传递的坐标。

I wouldn't say there is necessarily a "right" way to do it, however there are some good ideas you can follow. One of those ideas is to use HTTP REST verbs: use POST for "create" operations and GET for "read" operations. Given that, you should do an AJAX POST request to your server and pass the coordinates via POST parameters.

// will use this to turn an object into a url encoded string
var serializeObject = function(obj) {
  var output = '';
  for(var attr in obj) {
    if(obj.hasOwnProperty(attr)) {
      output += attr + '=' + obj + '&';
    }
  }
  return output.slice(0, -1);
};
var url = 'http://www.example.com/save.php';
// you need to serialize your data into key value pairs like the following
var exampleCoords = {
  x: 10,
  y: 20,
  z: 30
};
// postData will be x=10&y=20&z=30
var postData = serializeObject(exampleCoords);

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", postData.length);
request.setRequestHeader("Connection", "close");

// this function gets called when the request changes
request.onreadystatechange = function() {
    // request was successful
    if(request.readyState == 4 && request.status == 200) {
        alert(request.responseText);
    }
}
request.send(postData);

使用jQuery,你可以简化你的code相当多的(虽然它的pretty的多少做同样的事情在幕后):

Using jQuery you could simplify your code quite a bit (though it's pretty much doing the exact same thing behind the scenes):

var url = 'http://example.com/save.php';
var coords = {
   x: 10,
   y: 20,
   z: 30
};
$.post(url, coords).then(function(response) {
   console.log(response);
});

您可以通过访问在PHP中的变量 $ _ POST ['X'] ,一定要清理这些数据(的 ヶ辆 等)在MySQL中使用它之前。

You can access those variables in PHP using $_POST['x'], make sure you sanitize this data (htmlentities, etc.) before using it in MySQL.

有关的记录,AJAX和 XMLHtt prequest 有不同的名称,同样的事情,AJAX只是指异步JavaScript和XML(如 XMLHtt prequest ), XMLHtt prequest 是内置的对象,你用它来执行AJAX请求。

For the record, AJAX and XMLHttpRequest are different names for the same thing, AJAX is just referring to Asynchronous Javascript and XML (as in XMLHttpRequest), XMLHttpRequest is the built-in object you use to perform AJAX requests