最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make JQuery AJAX Run returned Script - Stack Overflow

programmeradmin2浏览0评论

I have a link, which I want to make a DELETE request with JQuery with AJAX.

if(confirm("Are you sure?")) {
   $.ajax({
    url: $(this).attr("href"),
    type: 'DELETE',
    success: function(result) {
            // Do something with the result
        }
    });
}

result is a wad of Javascript I would like to run. How do I get it to run my returned script?

I have a link, which I want to make a DELETE request with JQuery with AJAX.

if(confirm("Are you sure?")) {
   $.ajax({
    url: $(this).attr("href"),
    type: 'DELETE',
    success: function(result) {
            // Do something with the result
        }
    });
}

result is a wad of Javascript I would like to run. How do I get it to run my returned script?

Share Improve this question asked Jun 10, 2011 at 16:08 DrewDrew 15.4k19 gold badges69 silver badges78 bronze badges 4
  • 2 Please don't do that. Don't return Javascript code, don't eval, just return some kind of identifier and let your Javascript decide what to do. – kapa Commented Jun 10, 2011 at 16:10
  • @bazmegakapa Are you saying this for a separation of concerns purpose or is there a technical reason why this is a bad idea? – Drew Commented Jun 10, 2011 at 16:12
  • eval should be avoided whenever possible. I don't think there is a real reason for returning a piece of code. You could return some kind of JSON, and define in your Javascript what should happen to it. – kapa Commented Jun 10, 2011 at 16:14
  • Mainly security reasons. a Hacker may be able to inject malicious code into your site. – Jan Commented Jun 10, 2011 at 16:15
Add a comment  | 

3 Answers 3

Reset to default 14
success: function(result) {
    eval(result);
}

Use the dataType: 'script' option

$.ajax({
    url: $(this).attr("href"),
    type: 'DELETE',
    dataType: 'script'
});

Or simply,

$.getScript($(this).attr("href")); // Won't use 'DELETE' http type

Check the javascript Eval method. It allows you to execute js code which is represented as a string.

发布评论

评论列表(0)

  1. 暂无评论