[英]How to Pass PHP Array to Javascript as JSON Array
目前,我正在执行从Javascript到PHP文件的POST操作,以在PHP中执行操作并获取响应,但是在php文件中,我拥有Array,我想将其作为JSON Array接收到JavaScript。
Java脚本
$scope.details = function() {
$http({
method: 'POST',
url: 'myjson.json'
}).then(function(response)
})
PHP代码
<?php
header('Content-Type: application/json');
// index.php
// Run the parallel get and print the total time
$s = microtime(true);
// Define the URLs
$urls = array(
"url1",
"url2",
"url3"
);
$pg = new ParallelGet($urls);
//print "<br />total time: ".round(microtime(true) - $s, 4)." seconds";
// Class to run parallel GET requests and return the transfer
class ParallelGet
{
function __construct($urls)
{
// Create get requests for each URL
$mh = curl_multi_init();
$headers = array(
'authorization: Basic xyz',
'cache-control' => 'no-cache',
'Accept:application/json'
);
foreach($urls as $i => $url)
{
$ch[$i] = curl_init($url);
curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch[$i], CURLOPT_HTTPHEADER, $headers);
curl_multi_add_handle($mh, $ch[$i]);
}
// Start performing the request
do {
$execReturnValue = curl_multi_exec($mh, $runningHandles);
} while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
// Loop and continue processing the request
while ($runningHandles && $execReturnValue == CURLM_OK) {
// Wait forever for network
$numberReady = curl_multi_select($mh);
if ($numberReady != -1) {
// Pull in any new data, or at least handle timeouts
do {
$execReturnValue = curl_multi_exec($mh, $runningHandles);
} while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
}
}
// Check for any errors
if ($execReturnValue != CURLM_OK) {
trigger_error("Curl multi read error $execReturnValue\n", E_USER_WARNING);
}
// Extract the content
foreach($urls as $i => $url)
{
// Check for errors
$curlError = curl_error($ch[$i]);
if($curlError == "") {
$res[$i] = curl_multi_getcontent($ch[$i]);
//$finalResponse[] = $res[$i]->load();
} else {
print "Curl error on handle $i: $curlError\n";
}
// Remove and close the handle
curl_multi_remove_handle($mh, $ch[$i]);
curl_close($ch[$i]);
}
// Clean up the curl_multi handle
curl_multi_close($mh);
//print_r($res);
$responseArray = $res;
// Print the response data
$responseMSO = json_encode($res);
//print_r(utf8_encode(json_encode($res)));
//echo $finalResponse[1];
//echo $responseMSO;
}
}
?>
现在我想将它们作为JSONArray发送到Javascript
我已经看到了在PHP中使用json_encode的建议,但是当我使用它时,我得到的响应就是utf编码。
任何人请帮忙
我在下面介绍了所有内容,但没有太大帮助
尝试这个:
<?php
$myarray = array('{ "name":"中", "age":30, "car":null }','{ "name":"Mike", "age":32, "car":null }');
foreach ($myarray as $array) {
$arrays[] = json_decode($array);
}
echo json_encode($arrays, JSON_UNESCAPED_UNICODE);
echo '<br>';
echo json_encode($arrays);
?>
如您所见,第一个示例具有未转义的unicode
OUTPUT:
[{“ name”:“中”,“ age”:30,“ car”:null},{“ name”:“ Mike”,“ age”:32,“ car”:null}] [{“ name” : “\\ u4e2d”, “年龄”:30, “车”:空},{ “名”: “迈克”, “年龄”:32, “车”:空}]
现在我想将它们作为JSONArray发送到Javascript,如下所示
[{ "name":"John", "age":30, "car":null },{ "name":"Mike", "age":32, "car":null }]
OK,所以先设置php数组:
$myarray = array(
array(
'name' => 'John',
'age' => 30,
'car' => null
),
array(
'name' => 'Mike',
'age' => 32,
'car' => null
)
);
然后json在php中编码
echo json_encode($myarray);
结果: [{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]
有关使用json从php发送json响应的正确方法的更多详细信息,请看一下: 从PHP脚本返回JSON
如果您希望在PHP中转换对象数组并对其进行JSON编码,以便JavaScript可以使用结果,则这是一种实现此功能的方法:
<?php
$o = new stdClass;
$o->name = "John";
$o->age = 30;
$o->car =null;
$o2 = new stdClass;
$o2->name = "Mike";
$o2->age = 32;
$o2->car =null;
$myarray = [$o, $o2];
var_dump(json_encode($myarray));
// result:
"[{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]"
在这里查看示例。
为了使JSON编码的PHP对象数组对JavaScript有用,需要将其用单引号引起来,然后使用JSON进行解析,如下所示:
<script language="JavaScript">
var obj = JSON.parse('<?php echo json_encode($myarray) ?>');
console.log(obj[0].name + "\t" + obj[1].name); // John Mike
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.