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

时间:2010-01-28 18:23:00

标签: javascript jquery ajax forms

假设我有以下情况:

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

我的问题与something.php返回的JavaScript结果有关。我想参考表格。通常情况下,我会通过this引用(就像我上面的this.actionthis.method一样)。但是,当我返回以下内容时,这似乎不起作用:

alert(this);  // displays: [object Window]

看起来jQuery是在窗口的幌子下执行脚本而不是实例化事件的元素。有没有办法可以轻松引用实例化事件的对象,而无需在返回的JavaScript中引用元素ID或任何内容?

2 个答案:

答案 0 :(得分:1)

我发现我可以执行以下操作以允许响应中的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>

答案 1 :(得分:0)

尝试这样:

修改

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> 

“/something.php”中的js:

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