Calling a JavaScript function returned from an Aja

2019-01-01 02:12发布

I have a system where I send an Ajax command, which returns a script block with a function in it. After this data is correctly inserted in the DIV, I want to be able to call this function to perform the required actions.

Is this possible?

17条回答
君临天下
2楼-- · 2019-01-01 02:56

I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.

This is the example code provided by the jQuery API documentation:

function test()
{
  jQuery.globalEval("var newVar = true;")
}

test();
// newVar === true

This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.

查看更多
像晚风撩人
3楼-- · 2019-01-01 02:56

Federico Zancan's answer is correct but you don't have to give your script an ID and eval all your script. Just eval your function name and it can be called.

To achieve this in our project, we wrote a proxy function to call the function returned inside the Ajax response.

function FunctionProxy(functionName){
    var func = eval(functionName);
    func();
}
查看更多
爱死公子算了
4楼-- · 2019-01-01 02:57

This does not sound like a good idea.

You should abstract out the function to include in the rest of your JavaScript code from the data returned by Ajax methods.

For what it's worth, though, (and I don't understand why you're inserting a script block in a div?) even inline script methods written in a script block will be accessible.

查看更多
姐姐魅力值爆表
5楼-- · 2019-01-01 03:00

I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.

查看更多
孤独寂梦人
6楼-- · 2019-01-01 03:02

It is fully possible, and there are even some fairly legitimate use cases for this. Using the Prototype framework it's done as follows.

new Ajax.Updater('items', '/items.url', {
    parameters: { evalJS: true}
});

See documentation of the Ajax updater. The options are in the common options set. As usual, there are some caveats about where "this" points to, so read the fine print.

The JavaScript code will be evaluated upon load. If the content contains function myFunc(), you could really just say myFunc() afterwards. Maybe as follows.

if (window["myFunc"])
   myFunc()

This checks if the function exists. Maybe someone has a better cross-browser way of doing that which works in Internet Explorer 6.

查看更多
登录 后发表回答