【问题标题】:Help required in sending json to php server using POST method使用 POST 方法将 json 发送到 php 服务器所需的帮助
【发布时间】:2010-10-31 12:22:08
【问题描述】:

我正在尝试通过 POST 方法将 HTML 表单中的 json 数据发送回 php 服务器。这是我的代码。它会在回调函数中失败块。 Firebug 控制台(ctrl+shift+J)没有显示错误。

<script> 
function ADDLISITEM(form)
{ 
var options = form.txtInput.value;
options = JSON.stringify(options);
var url = "conn_mysql.php"
var request = null;
request = new XMLHttpRequest();
request.open("POST", url, true);
request.onreadystatechange = function(){
    if (request.readyState == 4) {
            if (request.status == 200) {
                alert(request.responseText);
        } else {
            alert(request.status); 
        }
    }
}
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));
}
</script>

conn_mysql.php

<?php  
    $json = $_POST['options'];
    $options = json_decode($json);
    $username = "user";  
    $password = "********";  
    $hostname = "localhost";  
    $dbh = mysql_connect($hostname, $username, $password) or die("Unable to 
    connect to MySQL");  
    $selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
    $query1 = "INSERT INTO user_spec (options) VALUES ('$options')";
    mysql_query($query1);
    //if(!mysql_query($query1, $dbh))
    //{die('error:' .mysql_error());} echo'success';
    $query = "SELECT * FROM user_spec";  
    $result=mysql_query($query);     
    $outArray = array(); 
     if ($result)
     { 
       while ($row = mysql_fetch_assoc($result)) $outArray[] = $row; 
     } 
      echo json_encode($outArray);
?> 

【问题讨论】:

  • 你想让我们给你写代码吗?
  • +1 Richards,@Harmen Stackoverflow 是一个帮助网站...
  • 了解您收到的 request.status 可能会有所帮助。如果不是200,那是什么? 404? 403? 500?
  • thanX steve,我刚刚在阅读您的评论之前这样做了,它是 404。php 文件名有错误。再次比X
  • 没问题。很高兴你明白了。

标签: php javascript ajax json


【解决方案1】:

您的请求显示“失败”,因为 onreadystatechange 函数以不同的 readyStates 多次调用。这是一个改进的、更好的缩进版本:

request.onreadystatechange = function(){
    if (request.readyState == 4) {
        if (request.status == 200) {
            alert('http.responseText');
        } else {
            alert('fail'); // fails here
        }
    }
}

您应该只在readyState 达到4 时检查status

此外,在为 URL 分配参数时,您应该使用 encodeURIComponent 正确编码参数(例如,在解析器认为它标志着新键/值对的开始的值中发送 &amp; 时)。当使用POST 作为方法时,您应该根据规范将%20 的所有实例更改为+ 并且将您的数据作为参数发送到send 函数,而不是将其连接到网址:

var url = "conn_sql.php";
…
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));

更新:要在 PHP 中处理发送的字符串,请使用json_decode,例如:

<?php
    $json = $_POST['options'];
    $options = json_decode($json);
    // now $options contains a PHP object
?>

(另见How to decode a JSON String

【讨论】:

  • 非常感谢 Marcel 提供的所有这些宝贵建议:-) 现在可以使用了。也有一个 php 脚本名称错误。现在我必须在 php 中的 POST 中捕捉到这一点。如果我遇到问题,我想我将不得不开始新的问题。
  • 另外,它没有使用 http.responseText 打印任何响应,我使用 request.responseText 并开始打印输出。
  • @XCeptable:确实,我错过了那个,但是您也必须删除该变量名周围的单引号。无论如何,不​​客气。我很高兴你成功了。
  • 还有一个问题。 'alert (request.responseText)' 应该打印我们发送到 url 的文本 JSON.stringify(options) 但它正在打印程序使用 getJson 从同一个 php 脚本接收到的数据。它昨天晚上被遗漏了没想到如果它进入成功块然后它不会再打印它应该是什么。
  • @XCeptable:不,那不是真的。变量request.responseText应该打印从您的 PHP 脚本接收到的数据。
猜你喜欢
  • 2020-02-16
  • 2015-11-18
  • 2013-12-06
  • 1970-01-01
  • 2021-08-04
  • 2011-08-02
  • 2017-06-19
  • 1970-01-01
相关资源
最近更新 更多