0 javascript php arrays ajax json
我在Javascript中有一个数组,它通过Ajax传递给PHP脚本.
在file.js中:
var params = {};
params["apples"] = "five";
params["oranges"] = "six";
params["pears"] = "nine";
var ajaxData = {data : params};
fetchData(ajaxData);
function fetchData(arg) {
$.ajaxSetup ({
cache: false
});
request = $.ajax ({
type: "GET",
url: "script.php",
data: arg,
});
request.done(function(response){
$("#somediv").text(response);
});
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
}
Run Code Online (Sandbox Code Playgroud)
在script.php中:
<?php
$data = json_decode(stripslashes($_GET['data']));
var_dump($data);
?>
Run Code Online (Sandbox Code Playgroud)
var_dump的结果是:
object(stdClass)#1 (3) { ["apples"]=> string(4) "five" ["oranges"]=> string(3) "six" ["pears"]=> string(4) "nine" }
Run Code Online (Sandbox Code Playgroud)
但我不想使用一个对象,我想使用它与我在Javascript中使用数据的方式相同(即:能够做到:
$apples = $data["apples"]
Run Code Online (Sandbox Code Playgroud)
有没有办法将这些数据作为数组处理,而不是从一开始就处理对象?如果没有,我如何将我现在拥有的内容转换为与Javascript中相同的关联数组?
谢谢.
PHP json_decode使用可选的第二个参数来执行此操作:
assoc
如果为TRUE,则返回的对象将转换为关联数组.
通过阅读文档解决了问题!
$data = json_decode(stripslashes($_GET['data']), true);
// ^^^^^^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |