问题
I am trying to learn more about jquery custom events so I have made this simple code to make tests:
<!DOCTYPE html>
<html>
<head>
<title>Jquery custom events</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function(){
$('#link1').click(function(){
var that = $(this);
$.ajax({
url: "http://localhost/jquery/index.html",
beforeSend: function(event){ // if returned false, stops ajax request
return that.trigger('ajax:beforesend',[{p1: '1'},{p2: '2'}]);
},
success: function(){
that.trigger('ajax:success');
},
error: function(){
}
});
return false;
});
$('#link1').bind('ajax:beforesend',function(e,data,data2){
alert("success"+data2.p2);
return false;
});
$('#link1').bind('ajax:success',function(e){
alert("success");
});
});
</script>
</head>
<body>
<a id="link1">link1</a>
<div id="box" style="width:500px;height:150px;background-color: gray;margin-top: 50px;">
result
</div>
</body>
</html>
My question is: in the beforesend function i want to abort the ajax request if the result of the triggered custom event is false but is not working, What i am missing?
EDIT: Please dont be focus on beforesend function. What i really want is how to return the custom event result (example true or false) to where the event was called (in this case before send function). As I said this is just boilerplate code. Not a real world project.
回答1:
beforeSend is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.
Please check the beforesend ajax event handler here and try http://api.jquery.com/jQuery.ajax/
Most probably your problem lies within the beforesend
function.
来源:https://stackoverflow.com/questions/10463218/jquery-custom-events-return-value