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.

图片转代码服务由CSDN问答提供 功能建议

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

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

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

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

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

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

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

谢谢。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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

相关推荐 更多相似问题