简体   繁体   中英

How do I get the value of an object by key in javascript?

I'm getting data using var result = $.getJSON.

When I console.log(result); I get this object:

Object
    abort: function (a){a=a||"abort",p&&p.abort(a),w(0,a);return this}
    always: function (){i.done.apply(i,arguments).fail.apply(i,arguments);return this}
    complete: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
    done: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
    error: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
    fail: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
    getAllResponseHeaders: function (){return s===2?n:null}
    getResponseHeader: function (a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c}
    isRejected: function (){return!!e}
    isResolved: function (){return!!e}
    overrideMimeType: function (a){s||(d.mimeType=a);return this}
    pipe: function (a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()}
    progress: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
    promise: function (a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}
    readyState: 4
    responseText: "{'result':'success'}"
    setRequestHeader: function (a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this}
    state: function (){return e}
    status: 200
    statusCode: function (a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this}
    statusText: "OK"
    success: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
    then: function (a,b,c){i.done(a).fail(b).progress(c);return this}
__proto__: Object

How do I get the value for the statusText key? (which in this case is "ok");

I've tried console.log(result.statusText) and console.log(result['statusText'] but both return as undefined. What gives?

EDIT: Here's the actual code I'm using.

 $j(".buyNowButton").click(function(){
      var qty = $j(this).attr('qty');
      var product_id = $j(this).attr("product_id");

      var params = "product_id=" + product_id + "&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;qty=" + qty;        

      var result = $j.getJSON("/acumen/scripts/addToCart.php", params, function(data, textStatus){
            console.log(textStatus);
           if (textStatus == "error"){
                alert("There was an error adding this item to your cart.  Please call customer service for assistance.", "Error");
                return;
           };
           if (data.result == "error"){
                alert("Sorry, an error occurred while adding the item to your cart.  The error was: '" + data.message + "'");
                return;
           };
      }); 
      console.log(result);
 });

It sounds like you're not using the object correctly. When you use console.log(result) , the only reason you're seeing the result text is because the Firebug console updates the reference values. If you tried to access result.statusText in code at that same line, you'd not get your result because the request likely hasn't actually finished yet.

This line:

var result = $.getJSON

Is giving you the request object itself. If you want to deal with the response, you do so in a callback function:

$.getJSON('request/url/goes/here', request_data, function(result) {
    // this is where you do something with your json data
});

... understanding that getJson is a "quick alias" for doing this:

$.ajax({
  url:'request/url/goes/here',
  dataType: 'json',
  data: request_data,
  success: function (result) {
      // this is where you do something with your json data
  }
});

You say that the response is the text "ok"; I would suggest then that you not use getJson , as that expects the response to be json data. Instead:

$.ajax({
  url:'request/url/goes/here',
  data: request_data,
  success: function (result) {
      // this is where you do something with your response string "ok"
  }
});

.. note that I am not specifying the data type of the callback as json. jQuery will auto-detect it.

Documentation

很简单:

result.statusText

your result variable is a promise that $.getJSON() returns, not your JSON data. You need to use a success callback.

Here is a simple example of how to use getJSON:

http://www.jquery4u.com/json/ajaxjquery-getjson-simple/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM