jQuery AJAX 调用返回 [object Object]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19584222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:14:46  来源:igfitidea点击:

jQuery AJAX call returns [object Object]

javascriptjqueryhtmlajax

提问by Vaughan Thomas

I am working on a Stock Exchange jQuery fix for a website.

我正在为一个网站进行证券交易所 jQuery 修复。

EDIT: It updates a ID/CLASS or input value on the webpage depending on the value returned.

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

index.php:

索引.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> 

Currently it is returning:

目前它正在返回:

[object Object]

I have also tried returning it to a div with .text()

我也试过用 .text() 将它返回到一个 div

demo.json:

演示.json:

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

Please can someone tell me what I did wrong.

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

Thanks in advance!

提前致谢!

回答by pala?н

You can do this:

你可以这样做:

// 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);
});

So the main issues here is:-

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

  • You need to do all the resultlogic in the ajax success callback, as ajax is asynchronousand you always get the empty values for the end& newendvariables.
  • No need to do this result = $( end * newend );as it creates a new jQuery object instance and hence you are getting [object Object]
  • 您需要result在 ajax 成功回调中执行所有逻辑,就像 ajax 一样,asynchronous并且您总是获得end&newend变量的空值。
  • 无需这样做,result = $( end * newend );因为它会创建一个新的 jQuery 对象实例,因此您将获得[object Object]

回答by Richard Peck

[object Object] is basically an array

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

Try this code:

试试这个代码:

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

This shouldshow you the array, which will give you the ability to better select the elements to output

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

回答by McRui

You're calculating the product inside $()

你在计算里面的产品 $()

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

回答by Scary Wombat

This code

这段代码

var end = parseInt($('#value').val());
var newend = parseInt($('#div').val());
var result = $( end * newend );

is being evaluated before the success of the ajax call. it needs to be moved into the success block

正在 ajax 调用成功之前进行评估。它需要移动到成功块中

回答by dagh

use the for loop like this code :

使用像这样的代码的 for 循环:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $( "select[name='continue[matiere]']" ).change(function () {
      var matiereID = $(this).val();


      if(matiereID) {


          $.ajax({
              url: "{{ path('ajaxform') }}",
              dataType: 'Json',
              data: {'id':matiereID},
              type:'POST',
              success: function(data) {
                  $('select[name="continue[chapitre]"]').empty();
                  for(i = 0; i < data.length; i++) {  
                    student = data[i];  

                      $('select[name="continue[chapitre]"]').append('<option value="'+ student['id'] +'">'+ student['nom'] +'</option>');
                  };
              }
          });


      }else{
          $('select[name="continue[chapitre]"]').empty();
      }
  });
  </script>