从 php 响应 AJAX 的更好方法

Better way to response to AJAX from php

本文关键字:更好 方法 AJAX php 响应      更新时间:2023-09-26

我有一个javascript文件,它将AJAX请求发送到php文件,该文件从数据库中获取一些数据。如果 php 找到任何数据,它会将其作为 json 对象作为响应返回,但是当它在数据库中找不到任何基于查询的记录时,它会返回一条类似"未找到匹配"的消息。这意味着javascript要么在"未找到匹配"或json对象中获取字符串消息。我正在尝试检查xmlhttp.responseText是json对象还是字符串,但尚未被成功。关于如何解决这个问题的任何想法?我应该将"未找到匹配"字符串转换为 json 并发送回 javascript 然后解析它,还是有更好的方法来解决这个问题?谢谢BR

我认为您不需要解析错误消息"找不到匹配项"。有两种选择:要么在 ajax 调用的 PHP 文件中创建一个 if/else 语句,要么尝试在 php 文件中对 JSON 进行编码,如果不成功,您可以在错误部分写出"找不到匹配项"消息。我强烈建议使用 $.ajax 调用,因为它可以更好地处理响应。

.JS

$.ajax({
    url: "myFile.php",
    dataType: "json",
    success: function(data) {
         var myNewJsonData = data;
         alert(myNewJsonData);
    },
    error: function() {
         alert("No match found.");
    }
});  

PHP (myFile.php)

<?php
    //Do your query business and stuff here
    //Now let's say you get back or store some array that looks like this for example
    $myArray = array('name' => 'Mike', 'age' => 20);

    /* Now attempt to create a JSON representation of the array using json_encode() */
    echo json_encode($myArray);        
?>

当你回显它时,它会通过$.ajax的调用successerror函数作为参数(我将其命名为data)发送回去,具体取决于是否有错误报告回来。如果没有,则调用success,如果有错误,那么您可以猜测调用了哪一个。 json_encode将创建从查询中返回的数据数组的 JSON 表示形式。

也许我不明白你的问题,你不能用这样的东西打印出一个错误:

$.ajax({
    url: "myphpfile.php",
    dataType: "json",
    success: function(data){
        alert(data.info);
    },
   error: function(xhr, status, error) {
            alert(status);
            alert(xhr.responseText);
            alert(xhr);
        }
     });

然后在error块内做点什么?

尽管我完全同意Patrick Q的评论,但还有另一种选择没有被提及。 您还可以设置响应的内容类型,以指示它是 json 还是文本:

@header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );

@header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) );

甚至,

@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );

然后,您可以检查响应的内容类型以做出决定:

$.ajax({
  type: "POST",
  url: "xxx", 
  data: "xxx", 
  success: function(response, status, xhr){ 
      var ct = xhr.getResponseHeader("content-type") || "";
      if (ct.indexOf('html') > -1) {
          //do something
      } else
      if (ct.indexOf('json') > -1) {
          // handle json here
      } 
  }
});

一个。