JSON 到 JavaScript

发布于 2024-10-25 18:51:22 字数 1810 浏览 3 评论 0原文

我正在尝试使用 JSON,我从服务器获取信息,所以我编写了这个 PHP 文件:

     include("db_connect.php");

      mysql_connect($host,$username,$password);
      @mysql_select_db($database) or die( "Unable to select database");

      $result = mysql_query("SET NAMES utf8");
      $query = "SELECT * FROM models WHERE models.product_id='".$product_selected."'";
      $result = mysql_query($query);
      $json_object =  "{ \"model\": [";

       while($result_row = mysql_fetch_row($result)) {
         $json_object .= " {\"model_name\" : \"".$result_row[1]."(".$result_row[2].")";
         $json_object .= "\"},";

        }
           $json_object = substr($json_object,0,strlen($json_object)-1);
           $json_object .= " ]};";

           echo  json_encode($json_object);

?>

PHP 文件的输出采用 JSON 格式,如下所示:

{ "model":
           [
              {"model_name" : "xxxxx "},
              {"model_name" : "xxxxx "},
              {"model_name" : "link2(U)"},
              {"model_name" : "xxxxx)"}
           ]
  };

但我在 Ajax 中得到如下响应:

var my_JSON_object = {};
var xmlHttp = createXmlHttpRequestObject();
  try {
         xmlHttp.open("GET", "ajaxproduct_new.php?product_id=" product_id,true);
         xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
              my_JSON_object = JSON.parse( xmlHttp.responseText );

             alert(my_JSON_object.model[0].model_name);
              }
  }
             xmlHttp.send(null);

   } catch (e){
           alert("Can't connect to server:\" e.toString());
}

但是当我对 my_JSON_object.model[0].model_name 发出警报时,它显示错误为 my_JSON_object.model 未定义。

为什么会这样来呢?我已经尝试了所有的东西。有人可以告诉我吗?

I'm trying to use JSON, I'm getting the information from the server so I've written this PHP file:

     include("db_connect.php");

      mysql_connect($host,$username,$password);
      @mysql_select_db($database) or die( "Unable to select database");

      $result = mysql_query("SET NAMES utf8");
      $query = "SELECT * FROM models WHERE models.product_id='".$product_selected."'";
      $result = mysql_query($query);
      $json_object =  "{ \"model\": [";

       while($result_row = mysql_fetch_row($result)) {
         $json_object .= " {\"model_name\" : \"".$result_row[1]."(".$result_row[2].")";
         $json_object .= "\"},";

        }
           $json_object = substr($json_object,0,strlen($json_object)-1);
           $json_object .= " ]};";

           echo  json_encode($json_object);

?>

The output of the PHP file is in JSON format like this:

{ "model":
           [
              {"model_name" : "xxxxx "},
              {"model_name" : "xxxxx "},
              {"model_name" : "link2(U)"},
              {"model_name" : "xxxxx)"}
           ]
  };

But i'm getting this response in Ajax like:

var my_JSON_object = {};
var xmlHttp = createXmlHttpRequestObject();
  try {
         xmlHttp.open("GET", "ajaxproduct_new.php?product_id=" product_id,true);
         xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
              my_JSON_object = JSON.parse( xmlHttp.responseText );

             alert(my_JSON_object.model[0].model_name);
              }
  }
             xmlHttp.send(null);

   } catch (e){
           alert("Can't connect to server:\" e.toString());
}

But when I'm doing alert of my_JSON_object.model[0].model_name it showing the error as
my_JSON_object.model is undefined.

Why is it coming like this? I have tried all the stuffs. Can any one please tell me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

被翻牌 2024-11-01 18:51:22

您正在创建一个看起来像 JSON 的字符串并将其传递给 json_encode,这是错误的。 json_encode 接受一个对象或数组。因此,创建一个数组而不是字符串:

$data = array();

while(($result_row = mysql_fetch_row($result))) {
    $data = array('model_name' => $result_row[1] . '(' . $result_row[2] .')');
}

echo json_encode(array('model' => $data));

您的 JavaScript 代码看起来没问题。

You are creating a string that looks like JSON and pass this to json_encode, which is wrong. json_encode accepts an object or an array. So, create an array instead of a string:

$data = array();

while(($result_row = mysql_fetch_row($result))) {
    $data = array('model_name' => $result_row[1] . '(' . $result_row[2] .')');
}

echo json_encode(array('model' => $data));

Your JavaScript code looks ok.

桃扇骨 2024-11-01 18:51:22

在知道 data 是什么之前尝试对 data.model[0].model_name 做任何事情对我来说听起来很糟糕。即使只是为了测试某些东西,eval也不会真正帮助你。

因此,调试的第一步是警告 xmlHttp.responseText 变量!

  • 如果它看起来不像您期望的那样,那么服务器就是问题所在。

  • 如果它看起来确实像您期望的那样,那么您的客户端存在一些问题(或者您错过了有关 json 中有效内容的一些内容)。

话虽这么说,菲利克斯的答案可能是正确的选择。

Attempting to do anything with data.model[0].model_name before you know what data is sounds bad to me. And even if it just for testing something, eval won't really help you.

So, the first step in debugging this would be to alert the xmlHttp.responseText variable!

  • If it doesn't look like you expect it to do, then the server is the issue.

  • If it does look like you expect it to do, then you have some problem client side (or you've missed something about what's valid in json).

That being said, Felix's answer is probably the right way to go.

李白 2024-11-01 18:51:22

尝试以下代码行
var data = eval("(" + xmlHttp.responseText + ")");
警报(数据.模型[0].模型名称)

try the following lines of codes
var data = eval("(" + xmlHttp.responseText + ")");
alert(data.model[0].model_name)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文