使用Ajax时,应该如何将变量从JavaScript传递到PHP?

问题描述:

Firstly, I'm aware that variations of this question has been asked before. However, in all prior example, the asker of the question has been using Ajax looking something like this:

$.ajax({
    type: "POST",
    url: 'logtime.php',
    data: "userID=" + userID;
});

However I am unfamiliar with this style. The way I have been taught to make Ajax requests is using code of the following form:

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php");
xhr.send();

xhr.onreadystatechange = function() {
    if(xhr.readyState === 4) {
        //DEFINE CALLBACK FUNCTION
    }
}

So, using the above Ajax style that I am familiar with, how should data be sent to the server to be processed by my php file data.php? I know it's something to do with including it in the xhr.send() parenthesis, but I'm not sure how exactly this is done?

Also, can the GET method be used if we wish to retrieve data from a database, but must provide a variable to the php in order for it to select the correct data from the database?

Lastly, what is the difference between the Ajax method I have been taught, and the other method I mentioned, which I often see mentioned on SO?

Thanks.

首先,我知道之前已经提出过这个问题的变体。 但是,在前面的所有示例中,问题的提问者一直在使用Ajax看起来像这样: p>

  $ .ajax({
 type:“POST”,
  url:'logtime.php',
 data:“userID =”+ userID; 
}); 
  code>  pre> 
 
 

但是我不熟悉这种风格。 我被教导制作Ajax请求的方式是使用以下形式的代码: p>

  var xhr = new XMLHttpRequest(); 
xhr.open(“GET”,“  data.php“); 
xhr.send(); 
 
xhr.onreadystatechange = function(){
 if(xhr.readyState === 4){
 // DEFINE CALLBACK FUNCTION 
} 
}  
  code>  pre> 
 
 

因此,使用我熟悉的上述Ajax样式,如何将数据发送到服务器以供我的php文件data.php处理? 我知道将它包含在 xhr.send() code>括号中是有意义的,但我不确定这是怎么做到的? p>

此外, 如果我们希望从数据库中检索数据,可以使用 GET code>方法,但是必须为php提供一个变量才能从数据库中选择正确的数据吗? p>

最后,我教过的Ajax方法和我提到的另一种方法之间有什么区别,我经常在SO上看到它? p>

谢谢。 p> div>

Please try:

  `xhr.send('you_user=user&your_password=password');`

... or can use something more elegant:

var d = new FormData();
d.append('you_user', 'user');
d.append('your_passowrd', 'password');
// ...
xhr.send(d);

There are a number of levels to this.

HTTP supports a number of methods which have different purposes.

To simply quite a lot, the main ones are GET and POST. GET is used to asking for data and POST is used when sending data to the server to change something.

In a GET request, any data you want to send to the server is typically encoded in URL using a query string (encoded using the application/x-www-form-urlencoded scheme.

In a POST request, the data is typically placed in the request body, and will usually also use application/x-www-form-urlencoded. If you wanted to upload files, then you would use multipart/form-data instead.

Encoding the data is probably most simply done using this algorithm:

(This isn't the most efficient way to do it, but it shows the steps clearly).

var data = [
    { key: "Foo", value: "a a a" },
    { key: "Bar", value: "b b b" },
    { key: "Baz", value: "c c c" }
];

var key_value_pairs = [];

for (var i = 0; i < data.length; i++) {
    var pair = encodeURIComponent(data[i].key) + "=" + encodeURIComponent(data[i].value);
    key_value_pairs.push(pair);
}

var query_string = key_value_pairs.join("&");

var url = "data.php" + "?" + query_string;

var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send();

If you wanted to make a POST request, then it is almost the same. You just change the end:

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php");
xhr.send(query_string);

Lastly, what is the difference between the Ajax method I have been taught, and the other method I mentioned, which I often see mentioned on SO?

It uses the jQuery library (but isn't a very good example of it). You can see where it constructs the query string manually ("userID=" + userID), but it fails to use the encoding routines. The safe approach when using jQuery is to pass an object to data instead:

$.ajax({
    type: "POST",
    url: 'logtime.php',
    data: { userID: userID }
});