jQuery AJAX调用返回[object Object]

时间:2013-10-25 07:55:13

标签: javascript jquery html ajax

我正在为网站开展股票交易所jQuery修复工作。

编辑:根据返回的值更新网页上的ID / CLASS或输入值。

的index.php:

<!doctype html>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<meta charset="utf-8">
<title>load demo</title>
<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
        url: '/datacall/demo.json',
        dataType: 'json',
        success: function( resp ) {
            $( '#div' ).val( resp.currency[0].amount );
        },
        error: function( req, status, err ) {
            console.log( 'Something went wrong', status, err );
        }
    });
    var end = parseInt($('#value').val());
    var newend = parseInt($('#div').val());
    var result = $( end * newend );
    $('#clickme').click(function() {
        $('#new').val( result );
    });
});
</script>

<div>

    <input type="hidden" value="2500" id="value" />

    <input type="hidden" value="" id="div">

    <input type="text" id="new" value="" readonly/>

    <input type="button" value="Change" id="clickme" />

</div> 

目前正在返回:

[object Object]

我也尝试使用.text()

将其返回到div

demo.json:

    { "currency" : [
  {
    "name" : "South Africa",
    "code" : "ZAR",
    "amount" : 0.14
  },
  {
    "name" : "America",
    "code" : "USD",
    "amount" : 0.64
  },
  {
    "name" : "Europe",
    "code" : "GBP",
    "amount" : 1.29
  }
] }

请有人告诉我我做错了什么。

提前致谢!

5 个答案:

答案 0 :(得分:18)

你可以这样做:

// Create some global variables
var end = parseInt($('#value').val(), 10);
var newend = 0;
var result = 0;

$.ajax({
    url: '/datacall/demo.json',
    dataType: 'json',
    success: function (resp) {

        // Check the values in console
        console.log(resp.currency[0].amount);
        console.log(resp.d.currency[0].amount);

        $('#div').val(resp.currency[0].amount);
        newend = parseInt(resp.currency[0].amount, 10);
        result = end * newend;

        // No need to create a new jQuery object using $()
        // result = $( end * newend );
    },
    error: function (req, status, err) {
        console.log('Something went wrong', status, err);
    }
});

$('#clickme').click(function () {
    $('#new').val(result);
});

所以这里的主要问题是: -

  • 您需要在ajax成功回调中执行所有result逻辑,因为ajax为asynchronous并且您始终获得end&amp;的空值。 newend个变量。
  • 无需执行此操作result = $( end * newend );,因为它会创建一个新的jQuery对象实例,因此您将获得[object Object]

答案 1 :(得分:14)

[object Object]基本上是一个数组

试试这段代码:

   success: function( resp ) {
       //$( '#div' ).val( resp.currency[0].amount );
       alert(JSON.stringify(resp));
    },

这个应该显示数组,这将使您能够更好地选择要输出的元素

答案 2 :(得分:2)

您正在计算$()

中的产品
var end = parseInt($('#value').val());
var newend = parseInt($('#div').val());
var result = end * newend; // this $(end * newend) is probably what was wrong

答案 3 :(得分:1)

此代码

var end = parseInt($('#value').val());
var newend = parseInt($('#div').val());
var result = $( end * newend );
在ajax调用成功之前正在评估

。它需要被移入成功块

答案 4 :(得分:0)

像下面的代码一样使用for循环:

NULL
相关问题