Place ajax $get() into a javascript variable

2019-09-10 05:46发布

问题:

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