Place ajax $get() into a javascript variable

故事扮演 提交于 2019-12-25 02:25:14

问题


I need to place the result of an ajax get into a javascript variable.

The following works

$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html)
{
    $("#divEdit").html(html);
});

This does not work

var editHtml = "";
$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html)
{
    editHtml= html;
});
$("#divEdit").html(editHtml);

Have also tried

var editHtml = "";
editHtml = $.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html)
{
    return html;
});
$("#divEdit").html(editHtml);

How can I get it to work?


回答1:


I've never tried using @Url.Action inside an $.ajax call (so I'm not 100% sure it works), but you could try using it since it gives you a more granular approach to ajax requests. In the success callback, you could

$.ajax({
    url: '@Url.Action("_Edit", "News", null)/' + guid_News,
    type: 'GET',
    //async: false,
    success: function(data) {
        $('#divEdit').html(data);
    }
});

$.ajax options even accept a parameter named async which you can set to false per your comment in @aroth's answer.




回答2:


The reason this does not work:

var editHtml = "";
$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html)
{
    editHtml= html;
});
$("#divEdit").html(editHtml);

...is because this part is a function closure:

function (html)
{
    editHtml= html;
}

It does not execute immediately, and it does not block execution of the statements that follow it. It will be executed when the server returns its response to the request, but by that time, your $("#divEdit").html(editHtml); statement has already executed with editHtml set to an empty string.

This should work:

var editHtml = "";
$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html) {
    editHtml= html;
    setDivHtml();
});

function setDivHtml() {
    $("#divEdit").html(editHtml);
}


来源:https://stackoverflow.com/questions/6920445/place-ajax-get-into-a-javascript-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!