【问题标题】:printing html and json results with jquery then()使用 jquery then() 打印 html 和 json 结果
【发布时间】:2012-11-05 13:44:45
【问题描述】:

我正在尝试学习使用 jquery deferreds。

在 jsfiddle 上使用 html 时,我得到一个返回的对象,当在 then() 语句中打印时,它有两行:“成功”和 ajax 请求返回的 html。

所以当我这样做时:

$(document).on('click', '.ajax', function() {
    $.when(ajax1('<p>first</p>'), 
           ajax2('<p>second</p>'), 
           ajax3('<p>third</p>'))
     .then(function(results1, results2, results3) {
        console.log(results1);
        $('.document').append(results1);
        $('.document').append(results2); 
        $('.document').append(results3);         
        alert('all ajax done');
    });
});

http://jsfiddle.net/loren_hibbard/AsgDz/

我在控制台中得到了这个:

["<p>first</p>", "success", 
Object
     abort: function ( statusText ) {
     always: function () {
     complete: function () {
     done: function () {
     error: function () {
     fail: function () {
     getAllResponseHeaders: function () {
     getResponseHeader: function ( key ) {
     overrideMimeType: function ( type ) {
     pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
     progress: function () {
     promise: function ( obj ) {
     readyState: 4
     responseText: "<p>first</p>"
     setRequestHeader: function ( name, value ) {
     state: function () {
     status: 200
     statusCode: function ( map ) {
     statusText: "OK"
     success: function () {
     then: function ( /* fnDone, fnFail, fnProgress */ ) {
          __proto__: Object

我怎样才能访问那个 responseText 并避免每隔一行显示“成功”的 html 输出:

first
success
second
success
third
success

而且由于我更可能将它与 JSON 数据一起使用,我该如何解析它。现在,虽然它在我的then() 函数中返回“ajax all complete”,但控制台中返回的对象是一组三个对象。一个是解析的 json 字符串,另一个是令人讨厌的字符串,上面写着“成功”,第三个是大对象,其中包含我未解析的 JSON 对象的 responseText。如何访问第一个对象并打印我解析的字符串? http://jsfiddle.net/loren_hibbard/jtvHf/1/

谢谢!

【问题讨论】:

    标签: javascript jquery json jquery-deferred


    【解决方案1】:

    简单修复——每个结果对象都是一个包含三个项目的数组:

    1. 结果数据
    2. 状态字符串(“成功”)
    3. JQXHR 对象。

    所以只需使用results1[0]等来获取数据:

     $('.document').append(results1[0].JSON);
    

    DEMO


    (注意,您的 ajax3 函数中似乎还有一个拼写错误——“类型”设置为 html 而不是 `post'。)

    【讨论】:

      猜你喜欢
      • 2012-12-05
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多