用Ajax获取php函数调用数组
问题描述:
I am working with php and call a php function with ajax:
<button onclick="loop()">Do It</button>
function loop() {
$.get("ajax.php", {
action: "true"
},
function(result) {
$("input").val(result);
});
}
PHP
if (isset($_GET["action"])) {
for ($i = 0; $i < 5; $i++) {
$array[] = array( "Value 1", $i );
}
echo $array;
}
My Input value will show this:
Now I would like to show the first array element. I modify the code like this:
$("input").val(result[0][0]);
My result:
But it has to be "Value 1"
Here is an overview of my array structure:
Array
(
[0] => Array
(
[0] => Value 1
[1] => 0
)
[1] => Array
(
[0] => Value 1
[1] => 1
)
[2] => Array
(
[0] => Value 1
[1] => 2
)
[3] => Array
(
[0] => Value 1
[1] => 3
)
[4] => Array
(
[0] => Value 1
[1] => 4
)
)
我正在使用php并使用ajax调用php函数: p>
&lt; button onclick =“loop()”&gt; Do It&lt; / button&gt;
function loop(){
$ .get(“ajax.php”,{
action:“true”\ n},
function(result){
$(“input”)。val(result);
});
}
code> pre>
PHP strong> p>
if(isset($ _ GET [“action”])){
for($ i = 0; $ i&lt; 5; $ i ++){
$ array [] = array(“Value 1”,$ i);
}
echo $ array;
}
code> pre>
我的输入值将显示: p>
现在我想展示第一个 数组元素。
我修改代码如下: p>
$(“input”)。val(result [0] [0]);
code>
我的结果: p>
但它必须是”值1“
以下是我的数组结构概述: p>
Array
(
[0] =&gt; 数组
(
[0] =&gt;值1
[1] =&gt; 0
)
[1] =&gt; 数组
(
[0] =&gt;值1
[1] =&gt; 1
)
[2] =&gt; 数组
(
[0] =&gt;值1
[1] =&gt; 2
)
[3] =&gt; 数组
(
[0] =&gt;值1
[1] =&gt; 3
)
[4] =&gt; 数组
(
[0] =&gt;值1
[1] =&gt; 4
)
)
code> pre>
div>
答
You'll need to return a format that javascript understands like JSON.
echo json_encode($array);
Then jQuery has a convenience method to automatically parse the returned JSON string:
$.getJSON("ajax.php", ...
Now result
will be a javascript array in your ajax response.