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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效