开发者

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 Technolog开发者_JAVA技巧ies"}}

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;"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜