繁体   English   中英

如何使用ajax从php文件中获取返回文本?

[英]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 响应,然后相应地获取文本。 然后您可以将其删除。

有两个变化要做:

  1. 由于您直接调用 PHP 文件,因此将type更改为“GET”。
  2. 删除成功函数中包裹的 j​​Query 方法并添加.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.

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