简体   繁体   English

完成AJAX调用后,通过PHP传递JavaScript函数

[英]Pass a JavaScript function with PHP after AJAX call is done

What I'm doing is checking a users status in the database. 我正在做的是检查数据库中的用户状态。

The PHP page echo's the status back to the ajax call and depending on the status a function is being executed. PHP页面将状态回传给ajax调用,并根据状态执行功能。

This works well. 这很好。 I know I could use json, but for now this is fine. 我知道我可以使用json,但现在就可以了。 What I'd like is not to echo the users status, but to echo the function that should be executed and execute it after ajax is done. 我想要的不是回显用户状态,而是回显应执行的功能,并在ajax完成后执行它。

My jQuery/ajax code: 我的jQuery / ajax代码:

function checkstatus() {
    $.ajax({
    type: "GET",
    url: "./query/checkstatus.php",
    data: {}
    }).done(function(result) {
      if (result == "nieuw") {
        loadHomeNieuw();
      };
      if (result == "actief") {
        loadHome();
      };
    });
}

What I'd like but is not working. 我想要但不起作用。 jQuery/ajax code: jQuery / ajax代码:

function checkstatus() {
    $.ajax({
        type: "GET",
        url: "./query/checkstatus.php",
        data: {}
    }).done(function(result) {
    });
}

PHP code (not working): PHP代码(无效):

if ($status == "nieuw") {
    echo "loadHomeNieuw();";
}

if ($status == "actief") {
    echo "loadHome();";
}

Is this even possible? 这有可能吗? The reason why I'm asking, is that I feel it's safer. 我问的原因是,我觉得它更安全。 It might be possible to hack the status as a user...so he can change it and the wrong function is being called. 可能会以用户身份入侵状态...以便他可以更改它并调用了错误的功能。 If I do this on the server side, it's way safer. 如果我在服务器端执行此操作,则会更安全。

Or are there better options? 还是有更好的选择?

You can call eval 你可以打电话给eval

function checkstatus() {
    $.ajax({
        type: "GET",
        url: "./query/checkstatus.php",
        data: {}
    }).done(function(result) {
        eval(result);
    });
}

but some people say that's evil so you can just return a name and execute a function that have that name: 但是有些人说这很邪恶,因此您可以返回一个名称并执行一个具有该名称的函数:

function checkstatus() {
    $.ajax({
        type: "GET",
        url: "./query/checkstatus.php",
        data: {}
    }).done(function(result) {
        window[result]();
    });
}

and in php just echo name 在PHP中只是回显名称

if ($status == "nieuw") {
    echo "loadHomeNieuw";
} else if ($status == "actief") {
    echo "loadHome";
}

What you're looking for is called GetScript: http://api.jquery.com/jQuery.getScript/ 您正在寻找的叫做GetScript: http : //api.jquery.com/jQuery.getScript/

this wil execute the returned code. 这将执行返回的代码。 the code : 编码 :

$.getScript("./query/checkstatus.php");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM