0

我有以下 javascript

$.ajax({
    type: ... url: ... data: ... bla bla...

    success: function( html ) {

        var response = $( html ).filter( '#targetID' ).html();

        $( 'body' ).html( response ).show('slow');

    }
});

它工作正常,除了用 javascript 加载页面,javascript 消失。那么如何解决这个问题呢?

4

2 回答 2

1

您应该在正文中使用容器,而不是将代码直接放在正文中。

IE。在主体内添加 div 标签,这将是容器

<div class="container"></div>

然后在JS调用

 $( '.container' ).html( response ).show('slow');

这样,内容会加载到容器中,而不是直接加载到正文中,这将替换页面的所有内容,包括您在那里的 JS。

此外,当使用 Ajax 调用时,我相信它可以使代码更简洁,将响应传递给其他函数以进行处理。这样,您将拥有更小的功能来调试并且更容易理解代码。

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {

      //Here you pass the response to the other function
      processSuccess(data);
  },
  fail: function(data) {

      //Here you pass the response to the other function
      processFail(data);
  }

});

function processSuccess(response) {
     //Print the response in the console (ie. Firebug console) 
     //if console is available
     if(console) {
        console.log(response);
     }
};

function processFail(response) {
     //Print the response in the console (ie. Firebug console) 
     //if console is available
     if(console) {
        console.log(response);
     }
};

当然,命名空间内的所有内容都会使它变得更好。

于 2012-09-22T23:06:20.640 回答
0

您的意思是您正在通过 Ajax 请求获取 javascript。

在这种情况下,您需要真正确保其中包含正确的代码。因为兼容性是那种东西的婊子。我认为当他加载结果时,JQuery duos 一个 eval 函数,所以应该加载 js。但这可能是您的代码有一些通常在页面上被忽略的错误,但是当您将其与 eval 一起使用时,您会在某些浏览器中出错。

你用的是哪个兄弟?

将代码加载到指定的 div 后尝试评估代码。

于 2012-09-22T22:59:03.733 回答