[英]Return json on exit php
I have been using $.getJSON
in order to verify if a script has done its job properly, using exit("{'status':true}")
(or false) but now I need the script to return a value (or an array). 我一直在使用
$.getJSON
来验证脚本是否已正确完成其工作,使用exit("{'status':true}")
(或false)但现在我需要脚本返回一个值(或者数组)。 I see that I can't use exit('{ "status": $myarray}');
我看到我不能使用
exit('{ "status": $myarray}');
. 。 What can I use instead?
我可以用什么呢? I am new to php- is it possible to do something like
return '{ "status": $myarray}';
我是php的新手 - 有可能做一些像
return '{ "status": $myarray}';
or something alike? 或类似的东西? Thanks in advance
提前致谢
You can use the following function: 您可以使用以下功能:
json_encode($data);
See: http://php.net/manual/en/function.json-encode.php 请参阅: http : //php.net/manual/en/function.json-encode.php
In your php, use json_encode
as such: 在你的php中,使用
json_encode
:
<?php
header('Content-Type: application/json');
echo json_encode($myarray);
// or, `exit(json_encode($myarray))` if global scope (see *REF)
?>
and in your jQuery use getJSON
normally: 并且在你的jQuery中通常使用
getJSON
:
$.getJSON("test.php",function(result){
...
});
(*) REF: PHP - exit or return which is better? (*)REF: PHP - 退出或退货哪个更好?
`$jsonString = 'your json string'`
$jsonArray = json_encode($jsonString);
return $jsonArray
If you want return data just like as array or single data in json then Try this code 如果你想要像json中的数组或单个数据一样返回数据,那么试试这段代码吧
In php file write like this 在php文件中写这样的
$value = 'welcome';
echo json_encode($value);exit;
or
$value = array("Saab","Volvo","BMW","Toyota");
print_r(json_encode($value));exit;
I will post the way I did it, seems quite simple to me now. 我将按照我的方式发布,现在对我来说似乎很简单。 Thank you for your answers
谢谢您的回答
$json_array=array('status'=>$row);
exit(json_encode($json_array));
AJAX call: AJAX电话:
$.getJSON( "savefunctions/getVideos.php", function(response) {
if( response.status ) alert(response.status);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.