【问题标题】:javascript with XMLHttpRequest's open method: using post and its parameters带有 XMLHttpRequest 的 open 方法的 javascript:使用 post 及其参数
【发布时间】:2010-11-28 04:50:26
【问题描述】:

理想情况下,我网站的用户会在大约一个小时内向数据库服务器发送几百个帖子(基本上是在线实验)。实验是用js实现的,所以我尝试用一​​个XMLHttpRequest对象来post脚本收集的数据。

我不确定的是如何使用 POST 参数。我想为 $_POST 变量设置大约 8 个不同的键/值对,以便在发送到数据库服务器之前可以访问 .php 页面进行处理。我对从服务器本身检索任何信息不感兴趣,只发送它(这就是为什么,我不确定这是否是正确的方法,我将 readyState 条件设置为“1”/打开)。

这是我目前正在使用的脚本:

function postData(dataList) {

 var xmlhttp = new XMLHttpRequest();
 var processingUrl = "process_exercise_data.php";
 var POSTBody = "";
 POSTBody+="block_type="+encodeURIComponent(dataList[0]);
 POSTBody+="&block_number="+encodeURIComponent(dataList[1]);
 POSTBody+="&trial_type="+encodeURIComponent(dataList[2]);
 POSTBody+="&trial_number="+encodeURIComponent(dataList[3]);
 POSTBody+="&input_value="+encodeURIComponent(dataList[4]);
 POSTBody+="&output_value="+encodeURIComponent(dataList[5]);
 POSTBody+="&prediction_value="+encodeURIComponent(dataList[6]);
 POSTBody+="&error="+encodeURIComponent(dataList[7]);


 xmlhttp.open("POST",processingUrl,true);
 if (xmlhttp.readyState==4) {
  xmlhttp.send(POSTBody);
 }

}

主要目标是使用 POST 将键/值对发送到 .php 页面,同时保留在当前页面上(简单的 AJAX 请求,如果我没记错的话)。非常感谢任何 cmets 或建议!

请记住,我想要完成的只是让用户在特定条件下(超出此函数范围)以特定方式行事时,调用此函数并将此数据发布到服务器。不需要服务器响应文本。

编辑:

现在我的问题是:我还能在处理 php 页面中访问 $_POST 数组吗?这是一个例子:

$block_type = $_POST['block.type'];

【问题讨论】:

  • 你是从哪里学会为帖子数据设置标题的?任何基础教程都应该告诉你如何发布数据。

标签: php javascript post xmlhttprequest


【解决方案1】:

您不想设置请求标头。你想要的是发送请求body。身体应该是这样的

'block_type='+encodeURIComponent(dataList[0])+'&block_number='+encodeURIComponent(dataList[1])

等等。猜你明白了。正文是您传递给 XMLHTTPRequest 对象的send() 方法的内容。

【讨论】:

  • +1。只需添加它以解决“不需要服务器响应”位:响应是必要的,否则浏览器会认为请求失败。如果响应 body 不需要包含任何内容,那么服务器响应代码应该设置为“204 No Content”,或者可能设置为“201 Created”。在 PHP 中,这可以通过 header() 函数来实现,例如header("HTTP/1.1 204 无内容");
  • 嗯。嗯,是的,但我认为问题是关于客户端的。
【解决方案2】:

考虑使用 jQuery,它会让你的任务变得更容易。使用jQuery.post 方法你只需要提供data 哈希,你不必担心序列化、正确转义或readyState

【讨论】:

    【解决方案3】:

    您必须在readyState 更改之前调用send。

    替换

    xmlhttp.open("POST",processingUrl,true);
    if (xmlhttp.readyState=4) {
      xmlhttp.send(POSTBody);
    }
    

    xmlhttp.open("POST", processingUrl, false);
    xmlhttp.send(POSTBody);
    

    如果要处理响应,请添加定义xmlhttp.onreadystatechange

    xmlhttp.open("POST", processingUrl, false);
    xmlhttp.onreadystatechange = function () {
      if (this.readyState === 4) {
        // handle response
      }
    };
    xmlhttp.send(POSTBody);
    

    编辑:我还想提一下 = 不是 JavaScript 相等运算符,它是赋值运算符。使用=== 进行相等检查,使用== 进行类型转换相等检查。

    【讨论】:

    • 另外值得注意的是你必须在调用send()之前设置onreadystatechange,否则你的AJAX回调会随机失败。
    猜你喜欢
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多