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

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制