简体   繁体   中英

How to force DOM modifications done in success function persist within a jQuery.Ajax() call?

I am getting a JSON object from a webMethod by the call below and I set some textBox values based on the returned objects attributes.

Problem is, just for a moment my textBoxes are populated but then immidiately they return back to empty.

Do I make a mistake or I cannot make DOM elements modifications within a success function?

Thanks.

   var ajaxCallOptions = {
              type: "POST",
              contentType: "application/json; charset=utf-8",
              url: "/JQuery/Chapter16-AJAX/PersonWebServices.asmx/GetPerson",
              context:  document.body,
              data: JSONObject,
              dataType: "json",
              success: function(data, textStatus, XMLHttpRequest){
                  var myPerson = data;

                  jQuery("#"+"<%=txtFirstName.ClientID %>").val(myPerson.d.FirstName);
                  jQuery("#"+"<%=txtLastName.ClientID %>").val(myPerson.d.LastName);

              },
              error: function(XMLHttpRequest, textStatus, errorThrown){
                alert('Error: '+textStatus);
              } };

   jQuery.ajax(ajaxCallOptions);

The returned data is:

Additional Note: {"d":{"__type":"BusinessObjects.Person","FirstName":"Burak","Id":"001","LastName":"Ozdogan","Department":"Information Technologies"}}

and this is a function which is bound to click event in the form:

<asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="loadPerson($('.personId'));"/>

If your $.ajax() is fired via a submit the default behavior is likely happening, and reloading the page.

Use return false; or event.preventDefault() at the end of your submit handler if that is the case.

$('.mySubmitButton').submit(function() {
    // Send ajax request
    return false;
});

or:

$('.mySubmitButton').submit(function( event ) {
    event.preventDefault()
    // Send ajax request
});

This same technique is used for links created from <a href=''> elements when you want to prevent the default behavior, or for any other element that has a default behavior for that matter.

I suggest use of FireBug or similar to examine the content being returned by the AJAX call. Failing this, try alerting the data which is returned.

Is the data returned the expected data?

Thanks Patrick.

It worked after this modification:

<asp:Button ID="btnSearch" runat="server" Text="Search" 
OnClientClick="loadPerson($('.personId'), event); return false;"/>

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