开发者

ajax not working in jquery

Hi I am trying to call a file named load.php and retrieve the result through AJAX. But for reasons which I dont know, my code is not working. Here is my code:

$.ajaxSetup({
   cache:false
})
var ajax_load="<img src='loading.gif' alt='loading...' />";
var loadurl = "load.php";
$("#add").click(function(){
   $("#result").html(ajax_load).load(loadurl, null, function(responsetext){
       alert("response text: "+responsetext);
   });
});

add is the id of my button and result is the id of my div where I want the result.

By the time server is fetching the result I wanted the loading gif image to be running and when the loading has complete the content shud be displayed.

Also, I did not want the cache option to be set, so I made it false.

I have included all the necessary libraries and the files in the correct path. Can anyone开发者_高级运维 help me?


For posterity sake (considering the answer seems to have been resolved in the comments). The issue appears to have been a result of attempting to access the DOM prior to it being ready.

$("#add").click(function(){
  // Code...
});

The above code relies on the element with id "add" (I.E. <a href='#' id='add'></a>) existing in the DOM so that the function passed to click can be attached to its click event.

An essential way to avoid attempting to attach to an element's event before the element becomes available is to wait for the entire DOM to load. jQuery's ready method does this and accepts the code that needs to wait as a function parameter.

$(document).ready(function(){
  $("#add").click(function(){
    // Code...
  });
});

jQuery also overloads the $ method with the same functionality when passed a function. This provides the following convenient shorthand, which is often used instead.

$(function(){
  $("#add").click(function(){
    // Code...
  });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜