将JSON数据从Javascript发送到PHP?

时间:2011-12-22 04:56:22

标签: php javascript ajax json

如何在浏览器中将JSON数据从Javascript发送到服务器并让PHP在那里解析?

11 个答案:

答案 0 :(得分:53)

我在这里收到了很多信息,所以我想发布一个我发现的解决方案。

问题:从浏览器上的Javascript获取JSON数据到服务器,并让PHP成功解析它。

环境: Windows上的浏览器(Firefox)中的Javascript。 LAMP服务器作为远程服务器:Ubuntu上的PHP 5.3.2。

什么有效(版本1):
1)JSON只是文本。文本采用某种格式,但只是文本字符串。

2)在Javascript中,var str_json = JSON.stringify(myObject)给了我JSON字符串。

3)我在Javascript中使用AJAX XMLHttpRequest对象将数据发送到服务器:

request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]

4)在服务器上,PHP代码读取JSON字符串:

$str_json = file_get_contents('php://input');

这将读取原始POST数据。 $str_json现在包含来自浏览器的确切JSON字符串。

什么有效(版本2):
1)如果我想使用"application/x-www-form-urlencoded"请求标头,我需要创建一个"x=y&a=b[etc]"的标准POST字符串,这样当PHP获取它时,它可以将它放在$_POST关联数组中。所以,在浏览器中的Javascript中:

var str_json = "json_string=" + (JSON.stringify(myObject))

当我通过AJAX / XMLHttpRequest发送str_json时,PHP现在可以填充$ _POST数组,如上面的版本1所示。

显示$_POST['json_string']的内容将显示JSON字符串。在带有json字符串的$ _POST数组元素上使用json_decode()将正确解码该数据并将其放入数组/对象中。

我遇到的陷阱:
最初,我尝试使用application / x-www-form-urlencoded的头发送JSON字符串,然后尝试立即从PHP中的$ _POST数组中读取它。 $ _POST数组始终为空。那是因为它期待yval = xval& [rinse_and_repeat]形式的数据。它没有找到这样的数据,只发现了JSON字符串,它只是把它扔掉了。我检查了请求标头,POST数据正在正确发送。

同样,如果我使用application / json标头,我又无法通过$ _POST数组访问发送的数据。如果要使用application / json content-type标头,则必须通过php:// input访问PHP中的原始POST数据,而不是使用$ _POST。

的参考文献:
1)如何在PHP中访问POST数据:How to access POST data in PHP?
2)有关application / json类型的详细信息,其中一些示例对象可以转换为JSON字符串并发送到服务器:http://www.ietf.org/rfc/rfc4627.txt

答案 1 :(得分:16)

使用jQuery的javascript文件(清理但库开销):

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'
});

PHP文件(process.php):

directions = json_decode($_POST['json']);
var_dump(directions);

请注意,如果您在javascript中使用回调函数:

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'
})
.done( function( data ) {
    console.log('done');
    console.log(data);
})
.fail( function( data ) {
    console.log('fail');
    console.log(data);
});

你必须在你的PHP文件中返回一个JSON对象(以javascript格式),以便完成/成功'您的Javascript代码中的结果。至少返回/打印:

print('{}');

请参阅Ajax request return 200 OK but error event is fired instead of success

虽然对于任何更严重的事情,你应该使用适当的响应代码明确地发回一个合适的标题。

答案 2 :(得分:6)

使用AJAX的HTML输入字段的JavaScript(发送到服务器JSON,在PHP中解析JSON并发送回客户端)的简单示例:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<div align="center">
    <label for="LName">Last Name</label>
    <input type="text" class="form-control" name="LName" id="LName" maxlength="15"
           placeholder="Last name"/>
</div>
<br/>

<div align="center">
    <label for="Age">Age</label>
    <input type="text" class="form-control" name="Age" id="Age" maxlength="3"
           placeholder="Age"/>
</div>
<br/>

<div align="center">
    <button type="submit" name="submit_show" id="submit_show" value="show" onclick="actionSend()">Show
    </button>
</div>

<div id="result">
</div>

<script>
    var xmlhttp;

    function actionSend() {
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var values = $("input").map(function () {
            return $(this).val();
        }).get();
        var myJsonString = JSON.stringify(values);
        xmlhttp.onreadystatechange = respond;
        xmlhttp.open("POST", "ajax-test.php", true);
        xmlhttp.send(myJsonString);
    }

    function respond() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById('result').innerHTML = xmlhttp.responseText;
        }
    }

</script>

</body>
</html>

PHP文件ajax-test.php:

<?php

$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array

$lName = $response[0];
$age = $response[1];

echo '
<div align="center">
<h5> Received data: </h5>
<table border="1" style="border-collapse: collapse;">
 <tr> <th> First Name</th> <th> Age</th> </tr>
 <tr>
 <td> <center> '.$lName.'<center></td>
 <td> <center> '.$age.'</center></td>
 </tr>
 </table></div>
 ';
?>

答案 3 :(得分:4)

PHP有一个名为json_decode()的内置函数。只需将JSON字符串传递给此函数,它就会将其转换为PHP等效的字符串,数组或对象。

为了将其作为字符串从Javascript传递,您可以使用

将其转换为JSON
JSON.stringify(object);

或像Prototype

这样的库

答案 4 :(得分:4)

从客户端(HTML,Javascript,Vbscript ..等)向服务器端(PHP,ASP,JSP等)发送数据有3种相关方法

1. HTML form Posting Request (GET or POST).
2. AJAX (This also comes under GET and POST)
3. Cookie

HTML表单发布请求(GET或POST)

这是最常用的方法,我们可以通过此方法发送更多数据

<强> AJAX

这是异步方法,这必须以安全的方式工作,这里我们也可以发送更多的数据。

<强>曲奇

这是使用少量不敏感数据的好方法。这是处理数据的最佳方式。

在您的情况下您可以选择HTML表单或AJAX。但在发送到服务器之前,请自行验证您的json或使用http://jsonlint.com/

之类的链接

如果你有Json Object使用JSON.stringify(object)将它转换为String,如果你有JSON字符串就按原样发送它。

答案 5 :(得分:2)

使用JSON.stringify(yourObj)或Object.toJSON(yourObj)最后一个是使用prototype.js,然后使用你想要的任何东西,ajax或submit发送它,你按照建议使用json_decode({{3在php中解析它。然后你可以将它用作数组。

答案 6 :(得分:2)

我推荐使用jquery.post()方法。

答案 7 :(得分:1)

    <html>
<script type="text/javascript">
var myJSONObject = {"bindings": 11};
alert(myJSONObject);

var stringJson =JSON.stringify(myJSONObject);
alert(stringJson);
</script>
</html>

答案 8 :(得分:1)

这是带有易于重现代码的主要解决方案的摘要:

方法1(application / json + JSON.stringify)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/json")
xhr.send(JSON.stringify(data)); 

PHP端,您可以通过以下方式获取数据:

print_r(json_decode(file_get_contents('php://input'), true));

方法2(x-www-form-urlencoded + JSON.stringify)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("json=" + JSON.stringify(data)); 

PHP端,您可以通过以下方式获取数据:

print_r(json_decode($_POST['json'], true));

方法3(x-www-form-urlencoded + URLSearchParams)

var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(new URLSearchParams(data).toString()); 

PHP端,您可以通过以下方式获取数据:

print_r($_POST);

注意:https://caniuse.com/#search=URLSearchParams

答案 9 :(得分:0)

您可以轻松地将对象转换为urlencoded字符串:

function objToUrlEncode(obj, keys) {
    let str = "";
    keys = keys || [];
    for (let key in obj) {
        keys.push(key);
        if (typeof (obj[key]) === 'object') {
            str += objToUrlEncode(obj[key], keys);
        } else {
            for (let i in keys) {
                if (i == 0) str += keys[0];
                else str += `[${keys[i]}]`
            }
            str += `=${obj[key]}&`;
            keys.pop();
        }
    }
    return str;
}

console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));

// key=value&obj[obj_key]=obj_value&

答案 10 :(得分:-2)

我找到了简单的方法,但我知道它并不完美

1.将json分配给

如果你是JSON

var data = [
    {key:1,n: "Eve"}
    ,{key:2,n:"Mom"} 
];

in --- main.php ----

    <form action="second.php" method="get" >
                <input name="data" type="text" id="data" style="display:none" >
                <input id="submit" type="submit"  style="display:none" >

     </form>

    <script>

      var data = [
        {key:1,n: "Eve"}
        ,{key:2,n:"Mom"} ];

       function setInput(data){
         var input = document.getElementById('data');
         input.value = JSON.stringify(data);
        var submit =document.getElementById('submit');

       //to submit and goto second page
        submit.click();

    }


   //call function
   setInput(data);

    </script>

in ------ second.php -----

    <script>

printJson();

function printJson(){
 var data = getUrlVars()["data"];

//decode uri to normal character
data =  decodeURI(data);
//for special character , / ? : @ & = + $ #
data =  decodeURIComponent(data);
//remove  " ' " at first and last in string before parse string to JSON
data = data.slice(1,-1);
data = JSON.parse(data);
alert(JSON.stringify(data));

}

//read get variable form url
//credit http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}

</script>