最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Get javascript object from ajax request - Stack Overflow

programmeradmin0浏览0评论

How do I create a javascript object from an AJAX response?

This is what I'm currently doing:

PHP:

<?
echo '{status:"1", site:"example"}';
?>

JS:

success:function(data_response){
    var object = eval( data_response );
    console.log(object.url);
    }});

I'm currently getting "undefined" on the console. How is this done?

How do I create a javascript object from an AJAX response?

This is what I'm currently doing:

PHP:

<?
echo '{status:"1", site:"example."}';
?>

JS:

success:function(data_response){
    var object = eval( data_response );
    console.log(object.url);
    }});

I'm currently getting "undefined" on the console. How is this done?

Share Improve this question asked Sep 15, 2012 at 3:42 lisovaccarolisovaccaro 34k99 gold badges270 silver badges423 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Set the dataType of the ajax request to json, and the data_response will be an object already parsed to.

Or you could use $.getJSON also.

You can also try something like this:

PHP

<?
echo json_encode(array("status"=>1,"site"=>"example."));
?>

Ajax call here with your params in JS

$.ajax({
  url: url, // your url where the php is
  dataType: 'json', 
  data: data, //send data
//callback
  success: function(data_response){  
      alert(data_response.status);
      alert(data_response.site);
}
});

instead of making your own json notation use php built in json_encode

<?php
    return json_encode(array('status' => '1', 'site' => 'example.'));
?>

Also you're logging object.url but it should be object.site.

You may also need to set your header to return application/json instead of text/html. This can be done also by specifying the dataType type parameter in your AJAX request to json

If you want to parse a raw object string using eval, you must wrap the object notation code in parens:

var object = eval( '(' + data_response + ')' );

The following will choke the parser:

eval('{status:"1", site:"example."}')

But this will work as you expect:

eval('({status:"1", site:"example."})')

Edit: Please note, I don't necessarily endorse this solution. This is just so you understand what's needed if you're going to use eval.

发布评论

评论列表(0)

  1. 暂无评论