简体   繁体   中英

jquery ajax success callback difficulty

I have the following code:

@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>
<div data-role="page">
    <div data-role="header">
        ...</div>
    <div data-role="content">
        <a id="btnShowCustomers" data-role="button" href="#secondDiv"></a>
    </div>
    <div data-role="footer">
        ...</div>
</div>
<div id="secondDiv" data-role="page">
    <div id="list" data-role="content">
    </div>
</div>
<div id="customerDetailsDiv" data-role="page">
    <div data-role="content">
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function (event) {
        $('#btnShowCustomers').bind('vclick', function (event) {
            GetCustomers();
        });
    });

    function GetCustomers() {
        var webMethod = "Home/GetCustomers";
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: webMethod,
            data: "{}",
            dataType: "json",
            success: function (dataObj) {
                $(dataObj).each(function () {
                    if ($(this).CanConsume) {
                        alert('can consume');
                        $('<a href="#" data-date="' + $(this).DateActivated + '" data-id="' + $(this).ID + '">' + $(this).Name + '</a>').appendTo('#list');
                    }
                })
            }
        });
    }
</script>

From the server-side I'm returning a list of Customer objects. Customer has the following properties;

  • ID
  • CanConsume (bool)
  • Name
  • DateActivated

I want to iterate through the returned set of results and build anchor elements and append them to a div named list. Do you have any idea why this is not working? I get no javascript errors.

dataObj is a normal list of plain JavaScript (JSON) objects. Don't use jQuery to iterate over that as jQuery.each(...) iterates over DOM elements.

Just try

   ...
   success: function(dataObj){
      for(var i=0; i < dataObj.length; i++){
         var obj = dataObj[i];
          if (obj.CanConsume) {
              alert('can consume');
              ...
          }
      }
   }

That should work.

Otherwise try Firebug or the Chrome Dev Tools to inspect the response or to set a breakpoint in your success callback. That should give you enough information to fix the problem.

jQuery kills errors... unfortunately.

If that does not work, please post some JSON.

damn to quick, again:

$.each(dataObj, function (index, element) {
    if (element.CanConsume) {
           alert('can consume');
           $('<a href="#" data-date="' + element.DateActivated + '" data-id="' + element.ID + '">' + element.Name + '</a>').appendTo('#list');
       }
});

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