如何捕获异步Ajax响应到一个变量?变量、Ajax

由网友(成迷)分享简介:我想提出以下的jQuery AJAX调用一个codeigniter PHP函数:I am making the following jquery ajax call to a codeigniter php function:var html ="";$.ajax({type:"POST",url: "Ajax/ge...

我想提出以下的jQuery AJAX调用一个codeigniter PHP函数:

I am making the following jquery ajax call to a codeigniter php function:

    var html ="";

    $.ajax({
                        type:"POST",
                        url: "Ajax/getHtml",
                        data: { u : contents },
                        dataType: 'html',       
                        success: function(data) {
                            html = data;
                        },

                        error: function(jqXHR, textStatus, errorThrown) {
                                console.log('error');
                                console.log(jqXHR,textStatus, errorThrown);
                        }
                    });

                     console.log('html', html);

这是正常工作和HTML被返回成功,我可以看到,如果我登录数据到控制台。不过,我似乎并没有能够捕捉到一个JavaScript变量的HTML响应。我宣布一(HTML)在全球范围。当我看到控制台我看到的:

This is working correctly and html is being returned on success which I can see if I log 'data' to the console. However I don't seem to be able to capture the HTML response in a javascript variable. I have declared one (html) globally. When I look at the console I see:

html 
jquery-2.1.1.js:8623 XHR finished loading: POST "http://localhost/b1/Ajax/getHtml".

我没有经历过与JavaScript但这似乎失灵,所以我觉得这个问题是JavaScript的异步特性使脚本向前移动,而无需等待Ajax请求返回的结果。

I'm not experienced with javascript but this seems out of order, so I think the problem is that javascripts asynchronous nature causes the script to move forward without waiting for the ajax request to return results.

这是否有意义,我应该怎么解决这个问题?

Does this make sense and how should I fix this?

推荐答案

恐怕是不可能的。

如果你想要做一些与数据从AJAX返回的HTML,你应该这样做成功的函数内部,或拨打另一个函数,没有工作的retured值。

If you want to do something with the html data returned from the ajax, you should do it inside the success function, or call another function that does the job with the retured value.

阅读全文

相关推荐

最新文章