简体   繁体   English

在jQuery.ajax()中使用dataType'script'调用DOM元素的引用

[英]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 . 我的问题与something.php返回的JavaScript结果有关。 I want to reference the form. 我想参考表格。 Normally, I would reference via this (as I did with this.action and this.method above). 通常,我会通过this引用(就像我对this.actionthis.method所做的那样)。 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. 看起来jQuery正在以窗口的名义而不是实例化事件的元素来执行脚本。 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? 有没有一种方法可以轻松引用实例化事件的对象,而不必引用返回的JavaScript中的元素ID或其他内容?

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: 我发现我可以执行下列操作,使this在应对引用调用对象,但我觉得这更是一个比黑客应该要求的:

<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: HTML:

<div>
   <form id="myCorrectForm" action="/something.php" method="GET">
     <input type="submit" value="Click me" />
   </form>
</div>

js: 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": /something.php中的js:

alert($(window.parent.frmRef).attr('id'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM