duanjiyun7391 2016-09-13 14:44
浏览 55
已采纳

使用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.

  • 写回答

2条回答 默认 最新

  • drju37335 2016-09-13 14:52
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?