分享
为什么问答平台  ›  专栏  ›  技术社区  ›  XCeptable

使用post方法将json发送到php服务器时需要帮助 - Help required in sending json to php server using POST method

  •  0
  • XCeptable  · 技术社区  · 2 周前

    我尝试通过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>
    

    康纳MySq.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 回复  |  直到 8 年前
        1
  •  1
  •   Community Nathan Hughes    2 年前

    onreadystatechange readyState

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

    status 4

    encodeURIComponent & POST %20 + send

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

    json_decode

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

    How to decode a JSON String