简体   繁体   中英

how to replace div content with $.ajax like a $.post

The Objective:

Change my $.post to an $.ajax in order to syncronize it and display the message until request has finished.

I would like to know exactly how I could do that with an ajax request, my big problem is when I try to replace div content as what I have done it here using $.post

The code:

The view

 function NewVersion() {
     $.ajax({
         url: "/Valoration/NewVersion",
         type: "POST",
         async: false,
         success: function (data, status, xhr) {
             if (data.success) {

                 $.post(data.hvmHeaderPartialView, function (partial) { $('#divHvmHeader').html(partial); });

                 MessageNewVersionSucced();
             }
         },
         error: function (xhr, status, err) {
             alert(err);
         }
     }); 

The controller

public ActionResult HvmHeaderPartialView()
    {
        return PartialView("_HvmHeaderPartialView,", DetailHvmModel);
    }    


private ActionResult NewVersion()
    {

    var result = hvmService.addNewVersion(hvm);
        var HvmHeaderPartialView = Url.Action("HvmHeaderPartialView,");


        return Json(new
        {
            success = result,
            hvmHeaderPartialView= HvmHeaderPartialView,

        });
    }

Do you need to keep it async=false?

You could use $.load() to replace div content instead of using $.post . For example:

$('#divHvmHeader').load('ajax/test.html');

With a callback function:

$('#divHvmHeader').load('/Valoration/NewVersion', function() {
  MessageNewVersionSucced();
});

Note : MessageNewVersionSucced will execute only after the ajax call to '/Valoration/NewVersion' completed.

You stated

Change my $.post to an $.ajax in order to syncronize it...

I am not sure if you are using jQuery 1.8 but the jQuery site states

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the complete/success/error callbacks.

Your request will not be performed synchronously. This may be the root of your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM