jsfiddle - return html with jquery when

2019-08-28 22:16发布

while trying to echo back some html on jsfiddle using jquery deferreds, I'm not getting any data back.

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

I can't understand what I've done wrong here. Passing the data as an object or as JSON.stringify, neither seems to work. http://jsfiddle.net/VAy5g/

2条回答
三岁会撩人
2楼-- · 2019-08-28 22:49

A somewhat belated response to this question.

The problem is not your jQuery. That works fine. The only problem is your use of jsFiddle's /echo/html API. Compare your code:

data: {data: "test2"},

to working code:

data: {html: "test2"},

The property that specifies the response is data.html, not data.data.

This version of your code works as expected.

查看更多
男人必须洒脱
3楼-- · 2019-08-28 22:57

Try using an asynchronous method like deferred.pipe(). Some example is shown in stackoverflow thread 10253192 jquery - Understanding Deferred.pipe().

This is the jquery documentation relates to your problem, http://api.jquery.com/jQuery.when/. Read it careful and see the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request. Adapt the prototype of the when exactly and do noz seperate the function. Make sure that console.log is doing something at this place and alter it im a way your function does what you wish it to do and where it should do it. It might be better logging into text files.

查看更多
登录 后发表回答