gpt4 book ai didi

php - 有没有办法将ajax数据作为单独的变量而不是完整的HTML获取?

转载 作者:行者123 更新时间:2023-12-01 07:21:26 25 4
gpt4 key购买 nike

我正在尝试使用 jquery $.post 按书籍的第一个字母获取书籍行进入我的<td> </td>这是我 table 的一部分。

我的 table 看起来像:

<table id="myTable">

<thead>
<tr>
<th class="page">pages</th>
<th class="book_name">Book Name</th>
<th class="author">Author</th>
</tr>
</thead>

<tbody id="result_list">
<!--Here is data which will come with ajax($.post) -->
</tbody>
</table>

编写jquery代码,我成功了,但是$("#result_list").html(data)像这样:

$.post( "/ajax.php", { book_first_letter: 'A'},
function( data ) {
$( "#result_list" ).html( data );
}
);

但我不想将所有数据作为 HTML 获取并插入 <tbody> 。我想从 ajax.php 获取数据作为单独的变量。例如;书名、 Logo 、页数、作者。我想将它们插入 <td> </td>

我的ajax.php是这样的:

 $letter= trim($_POST['book_first_letter']);    
$query = $this->book_model->get_books_by_letter($letter);
foreach ($query as $book) { ?>

<tr>
<td> <?php echo $book->page; ?> </td>
<td> <?php echo $book->name; ?> </td>
<td> <?php echo $book->author; ?> </td>

</tr>
<?php
}
?>

有没有办法获取每个变量(即 $book->name)并将其插入 <td></td>

最佳答案

你不仅可以,而且应该。让 PHP 返回 JSON 对象,而不是让 PHP 以文本形式返回 html。

您需要做一些事情。首先向 $.post() 调用添加第四个参数,数据类型为“json”。

$.post( "/ajax.php", { book_first_letter: 'A'}, callback, "json" );

然后,让 PHP 发送结果的 JSON header 是一种很好的形式,因此在 PHP 中发送任何数据之前,请使用

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

无需回显图书模型的属性,只需使用 json_encode()

$letter= trim($_POST['book_first_letter']);    
$books = $this->book_model->get_books_by_letter($letter);
echo json_encode( $books );

所以客户端现在有了原始数据,您可以使用 js/jQuery 循环遍历书籍并将其添加到您的表中。

function callback( books)
{
var i = 0, len = books.length, html = "";

for( ; i < len; ; )
{
html += "however you want to structure the data";
}

$( "#result_list" ).html( html );
}

关于php - 有没有办法将ajax数据作为单独的变量而不是完整的HTML获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13364378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com