【问题标题】:jsfiddle - return html with jquery whenjsfiddle - 使用 jquery 返回 html 时
【发布时间】:2013-05-29 17:47:16
【问题描述】:

在尝试使用 jquery deferreds 在 jsfiddle 上回显一些 html 时,我没有得到任何数据。

function showData(data1, data2) {
    console.log(data1[0]);
    console.log(data2);
}

function method1() {
    return $.ajax({
        type: "post",
        url: "/echo/html/", 
        data: JSON.stringify("test1"),
        dataType: 'html'
    });
}

function method2() {
   return $.ajax({
        type: "post",
        url: "/echo/html/", 
        data: {data: "test2"},
        dataType: 'html'
    });
}

$.when(method1(), method2()).then(showData);

我不明白我在这里做错了什么。将数据作为对象或JSON.stringify 传递,似乎都不起作用。 http://jsfiddle.net/VAy5g/

【问题讨论】:

  • “似乎都不起作用”是什么意思?它似乎对我有用......
  • @darkajax ["", "success", Object] 打印到我的控制台。所以data1[0]data2[0] 中没有返回数据,我希望在该位置分别看到“test1”和“test2”。
  • 如果要回显json数据,ajax中的URL应该是url: "/echo/json"

标签: jquery jsfiddle jquery-deferred


【解决方案1】:

尝试使用像 deferred.pipe() 这样的异步方法。 stackoverflow 线程 10253192 jquery - 了解 Deferred.pipe() 中显示了一些示例。

这是与您的问题相关的 jquery 文档,http://api.jquery.com/jQuery.when/。仔细阅读并查看 jQuery.ajax() 文档以获取有关 ajax 请求成功和错误情况的完整描述。准确地调整when的原型,然后将函数分开。确保console.log 在这个地方做某事并改变它,因为你的函数做你希望它做的事情以及它应该做的事情。登录文本文件可能会更好。

【讨论】:

  • 我相信 pipe() 已被弃用。
【解决方案2】:

对这个问题的回答有点迟。

问题不在于你的 jQuery。这很好用。唯一的问题是您使用 jsFiddle 的 /echo/html API。比较您的代码:

data: {data: "test2"},

working code:

data: {html: "test2"},

指定响应的属性是data.html,而不是data.data

This version of your code 按预期工作。

【讨论】:

    猜你喜欢
    • 2010-11-27
    • 2011-11-03
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多