Home > Backend Development > PHP Tutorial > javascript - How does php return a json object when responding to ajax? Am I doing this right?

javascript - How does php return a json object when responding to ajax? Am I doing this right?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-03-02 08:42:01
Original
1013 people have browsed it

Is this how to echo json string?

<code>function my()
{
    ...
    
    echo {"code":"NO_ERROR","msg":"获取系统参数成功"}
}</code>
Copy after login
Copy after login

Reply content:

Is this how to echo json string?

<code>function my()
{
    ...
    
    echo {"code":"NO_ERROR","msg":"获取系统参数成功"}
}</code>
Copy after login
Copy after login

<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>
Copy after login

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");

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template