[英]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.