简体   繁体   English

如何在JS中使用ajax请求的结果?

[英]How to use the result of an ajax request in JS?

I have a query which returns 2 rows. 我有一个返回2行的查询。 Here is my PHP code: 这是我的PHP代码:

$arr = array();

$stmt = $dbh_conn->prepare("SELECT id,name FROM mytable WHERE id <= 2");
$stmt->execute();
$result = $stmt->fetchAll();
/*Array
  (
      [0] => Array
          (
              [id] => 1
              [name] => pear
          )

      [1] => Array
          (
              [id] => 2
              [name] => watermelon
          )

  ) */

$arr["output"] = $result;

header('Content-Type: application/json');   
echo json_encode($arr);
exit(); 

And here is my JS code: 这是我的JS代码:

success: function(arr) {
    $(".myclass").html(arr.output.0.name);
}

And it throws this: 它抛出这个:

Uncaught SyntaxError: missing ) after argument list 参数列表后面的Uncaught SyntaxError:missing)

When I remove .0.name , it throws this: 当我删除.0.name ,它抛出这个:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. 未捕获的TypeError:无法在'Node'上执行'appendChild':参数1不是'Node'类型。

Anyway, how can I show the result of a ajax request when there is multiple rows selected? 无论如何,当选择多行时,如何显示ajax请求的结果?

All I want to make is a HTML table of the result like this: 我想要的是一个结果的HTML表,如下所示:

<tr>
    <td>1</td>
    <td>pear</td>
</tr>
<tr>
    <td>2</td>
    <td>watermelon</td>
</tr>

And then push it into $('.myclass') element. 然后将其推入$('.myclass')元素。

Use JSON.parse to parse the string ( data ) back into an array. 使用JSON.parse将字符串( data )解析回数组。

success: function(data) {
    var arr = JSON.parse(data);
    $(".myclass").text(arr.output[0].name);
}

And use subscripts for arrays. 并使用数组的下标。 And if you want to set the text of the .myclass as mentioned in a comment use .text instead of .html . 如果你想设置.myclass中提到的.myclass的文本,请使用.text而不是.html

If your data is returned as json, you need to access the array of objects, change 如果您的数据以json的形式返回,则需要访问对象数组,进行更改

$(".myclass").html(arr.output.0.name);

to

$(".myclass").text(arr.output[0].name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM