繁体   English   中英

使用ajax调用php函数时遇到问题

[英]having problems using ajax to call a php function

在clientside(js)即时通讯上使用此脚本

    jQuery.ajax({
    type: "GET",
    url: "editold.php",
    data: "call=generateCode",
    success: function (response) {
        alert("Succesful getting php file");
    },
    error: function (response) {
         alert("Error getting php file");
    }
});

在serverside(php)即时通讯使用此代码:

<?php 



if($_SERVER['REQUEST_METHOD']=="GET") {
echo '<script type="text/javascript">' . 'alert(" ' . 'hey' . '");' . '</script>'; 
$function = $_GET['call'];

    if(function_exists($function)) {        
        call_user_func($function);
    } 
    else {
        echo 'Function Not Exists!!';
    }
}

function generateCode() {
echo '<script type="text/javascript">' . 'alert(" ' . 'hey' . '");' . '</script>'; 
}
?>    

虽然我确实得到一个警告说我的成功函数警报意味着文件已成功加载我似乎没有让最终的generatecode函数工作。(我没有得到第二个警报。)

我尝试过很多东西,但似乎没什么用。

我该怎么办?..

这应该这样做:

jQuery.ajax({
    type: "GET",
    url: "editold.php",
    data: {call: "generateCode"}, // <-- This one is changed into an object
    success: function (response) {
        alert("Succesful getting php file");
        $('body').append(response); // <-- Append the ajax response to the page body
    },
    error: function (response) {
        alert("Error getting php file");
    }
});

如果没有,请尝试执行var_dump($_GET); 在你的PHP文件中。

1 - 在服务器端发送没有脚本标记的响应。

2 - 在客户端使用eval()函数来执行代码。

if($_SERVER['REQUEST_METHOD']=="GET") {
echo 'alert(" ' . 'hey' . '");';
$function = $_GET['call'];

if(function_exists($function)) {        
    call_user_func($function);
} 
else {
    echo 'Function Not Exists!!';
}
}

function generateCode() {
//your code 
}


jQuery.ajax({
    type: "GET",
    url: "editold.php",
    data: "call=generateCode",
    success: function (response) {
        alert("Succesful getting php file");

        eval(response);
    },
    error: function (response) {
        alert("Error getting php file");
    }
});

暂无
暂无

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

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