dsgdg54ef4365
2018-01-17 09:25
浏览 53

用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:

enter image description here

Now I would like to show the first array element. I modify the code like this:

 $("input").val(result[0][0]);

My result:

enter image description here

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
        )

)

图片转代码服务由CSDN问答提供 功能建议

我正在使用php并使用ajax调用php函数:

  &lt; button onclick =“loop()”&gt; Do It&lt; / button&gt; 
 
function loop(){
 $ .get(“ajax.php”,{
 action:“true”\  n},
 function(result){
 $(“input”)。val(result); 
}); 
} 
   
 
 

< strong> PHP

  if(isset($ _ GET [“action”])){
 for($ i = 0; $ i&lt; 5;  $ i ++){
 $ array [] = array(“Value 1”,$ i); 
} 
 echo $ array; 
} 
   
 
 

我的输入值将显示:

现在我想展示第一个 数组元素。 我修改代码如下:

  $(“input”)。val(result [0] [0]); 
  <  / pre> 
 
 

我的结果:

但它必须是”值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 
)
 
)
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulvyi2172 2018-01-17 09:32
    已采纳

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题