Home > Article > Backend Development > javascript - How does php return a json object when responding to ajax? Am I doing this right?
Is this how to echo json string?
<code>function my() { ... echo {"code":"NO_ERROR","msg":"获取系统参数成功"} }</code>
Is this how to echo json string?
<code>function my() { ... echo {"code":"NO_ERROR","msg":"获取系统参数成功"} }</code>
<code>$.ajax({ type: "GET", url: "http://www.example.com/json.php", data: {name:"ele", pass:"123"}, //这里的data是参数,跟下面回调函数里服务器返回的data不是一个东西 success: function(data){ console.log(data); } }); <?php $arr = array( 'code' => 'NO_ERROR', 'msg' => '获取系统参数成功', ); header('Content-Type: application/json; charset=utf-8'); echo json_encode($arr);</code>
Although I don’t know your specific problem scenario, I will answer based on my development experience. I have encountered json returned by java calling php, but when json_encode an empty array, java cannot recognize it. At this time You need to make an additional judgment. You need to judge whether the object you pass in is empty: json_encode(array('data' => (empty($data) ? new stdclass() : $data)))
It is easy to make mistakes when writing strings yourself, such as special strings, etc. It is recommended to use json_encode($obj), a powerful php method
In fact, it is not necessary. It is too troublesome to write like this. It is usually written as an array. Then json_encode is enough
$this->ajaxReturn(json_encode($data), "JSON");