jquery评估一个javascript文件

时间:2011-11-15 07:45:03

标签: javascript jquery html post

如何使用jQuery发布请求并查看结果。

我有一个format.js文件,如果我在浏览器的url上输入,就会返回这样的内容。

document.write( '<object    id="player" name="YOUniversityTVPlayer"    type="application/x-shockwave-flash"    allowFullScreen="true">' );

我使用:

$.post(
    "format.js", function(data) {alert("success");alert(data);}
);

我希望警报显示请求的结果,即format.js结果

2 个答案:

答案 0 :(得分:1)

只需删除已加载脚本中的document.write即可!当您的脚本由$.post评估时,参数data的实际值是脚本的最后一个表达式语句的结果。举个例子,考虑一下:

val r = eval("dosomethingelse(); 42"); // r is 42

如果因任何原因无法更改加载的脚本,您可以随时劫持document.write

var oldwrite = document.write;
var mypreciousdata;
document.write = function (data) {mypreciousdata = data;}
// your $.post here
document.write = oldwrite;

但我确实谴责这些行为......

答案 1 :(得分:0)

也许你应该做一些不同的事情,比如保存

<object    id="player" name="YOUniversityTVPlayer"    type="application/x-shockwave-flash"    allowFullScreen="true">

在名为fragment.html的文件中,使用$ .ajax获取,然后使用片段

$.ajax({
  url: "fragment.html",
  dataType: "html",
  method: "post",
  success: function(data, textStatus, jqXHR){
     alert(data);
     //use the html
     $('#result').html(data);
  });

您也可以使用“script”作为dataType并随时评估脚本,但当然您需要更改脚本