[英]How to get return text from php file with ajax?
我正在用 ajax 調用一個 php 文件。 我想要做的就是從 php 文件中取回一個值,用 javascript 測試它。 我嘗試了很多很多東西,但只能得到未定義(從下面的代碼)。
如何從 php 文件返回“你好”到我的 javascript?
jQuery.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = jQuery(data).html();
alert(the_returned_string)
}
});
PHP文件:
<?php
echo '<div id="id-query-result>"';
echo "hello";
echo "</div>";
您可以像這樣更改 PHP 中的代碼
<?php
$queryResult = '<div id="id-query-result">hello</div>';
echo json_encode(['html' => $queryResult]);
然后,更改您的 ajax 調用
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
dataType: 'json',
success: function(data) {
var the_returned_string = data.html;
alert(the_returned_string);
}
});
$.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
$('body').append(data);
var text = $('#id-query-result').text();
alert(text);
$('#id-query-result').remove()
}
});
為什么不直接附加 php 文件的 HTML 響應,然后相應地獲取文本。 然后您可以將其刪除。
有兩個變化要做:
type
更改為“GET”。.html
作為屬性jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = data.html
alert(the_returned_string)
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.