[英]calling function from php file inside javascript
我已经编写了这段代码来从javascript调用php函数,该php函数只是简单地打印了它接收到的参数,但是这段代码没有给出任何输出,也没有输出任何内容,我使用的是Google chrome浏览器,请帮忙。
index.html文件
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
jQuery.ajax(
{
type: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["username", "password"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
</script>
</head>
</html>
save.php文件
<?php
header('Content-Type: application/json');
if( $_POST['functionname'] == 'saveUser' ) {
echo json_encode(Array(
result => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
));
}
?>
有一个错字。 您缺少引号数组键
尝试这个
echo json_encode(Array(
'result' => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
^ ^
));
您的save.php文件中存在语法错误。 用字符串引号将结果索引括起来。 先修好
if( $_POST['functionname'] == 'saveUser' ) {
echo json_encode(Array(
'result' => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
/*^^^^*/
));
}
而在index.html中,只需在ajax成功代码下方添加即可。
success: function (obj, textstatus) {
if( !('error' in obj) ) {
document.write(obj.result); //This line
alert(obj.result);
}
else {
console.log(obj.error);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.