Reference calling DOM element in jQuery.ajax() with dataType 'script'
Let's say I have the following scenario:
<form action="/something.php" method="GET">Click me</div>
<script type="text/javascript"><!--
$('form').submit(function(e) {
$.ajax({
url: this.action,
method: this.method,
dataType: 'script'
});
return false;
开发者_运维问答 });
//--></script>
My question pertains to the JavaScript result returned by something.php
. I want to reference the form. Normally, I would reference via this
(as I did with this.action
and this.method
above). However, that doesn't seem to work when I return the following:
alert(this); // displays: [object Window]
It looks like jQuery is executing the script under the guise of the window instead of the element that instantiated the event. Is there a way I can easily reference the object that instantiated the event without having to reference element ID's or anything within the returned JavaScript?
I found that I can perform the following to allow this
in the response to reference the calling object, but I feel like this is more of a hack than should be required:
<form action="/something.php" method="GET">Click me</div>
<script type="text/javascript"><!--
$('form').submit(function(e) {
$.ajax({
url: this.action,
method: this.method,
dataType: 'text',
success: function(data) {
eval('(function() {' + data + '}).call(this);');
}
});
return false;
});
//--></script>
try in this way:
EDIT:
html:
<div>
<form id="myCorrectForm" action="/something.php" method="GET">
<input type="submit" value="Click me" />
</form>
</div>
js:
<script type="text/javascript"><!--
// in this environment is created for the variable "frmRef" public
var frmRef = null;
$('#myCorrectForm').submit(function(e) {
frmRef = $(this);
$.ajax({
url: frmRef.attr("action"),
method: frmRef.attr("method"),
dataType: 'script'
});
return false;
});
//--></script>
js in "/something.php":
alert($(window.parent.frmRef).attr('id'));
精彩评论