我不确定我做错了什么,但我有一个PHP函数,我需要从中检索一些数据。
我正在使用JQuery 1.11来执行ajax函数
$(document).ready(function() {
$('#butt_example').on('click', function() {
$.ajax({
url : 'scripts/functions.php',
type : 'GET',
dataType : 'json',
data : {
'action': 'test'
},
success: function(result) {
var la_result = JSON.parse(result);
console.log(la_result);
},
error: function(log) {
console.log(log.message);
}
});
});
});
然后我用一个简单的替换我的php函数进行测试
<?php
if(isset($_GET["action"])) {
$arr = array();
$arr[0] = "test";
$arr[1] = "passed";
header('Content-Type: application/json; charset=utf-8');
echo json_encode($arr);
}
?>
但是,当我单击按钮执行代码时,我发现控制台日志结果未定义。
为什么会这样?
更新
在Mike的评论之后,我意识到它实际上是在错误条件下执行控制台日志。
所以它失败了,我不知道为什么
答案 0 :(得分:0)
你确定AJAX调用能够到达PHP函数吗?
试试这个 在.php文件中首先执行此操作
这将产生类似于codeigniter或任何其他相对框架的base_url()。
function url(){
return sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['SERVER_NAME'],
$_SERVER['REQUEST_URI']
);
}
<script>
var url="<?php echo url(); ?>";
</script>
然后在您的JS文件中提供URL
$(document).ready(function() {
$('#butt_example').on('click', function() {
$.ajax({
url : url+'scripts/functions.php',
type : 'GET',
dataType : 'json',
data : {
'action': 'test'
},
success: function(result) {
var la_result = JSON.parse(result);
console.log(la_result);
},
error: function(log) {
console.log(log.message);
}
});
});
});
正如所指出的,为http和https修改了网址提取。
答案 1 :(得分:0)
正如您从the manual所见:
错误强>
类型:函数(jqXHR jqXHR,String textStatus,String errorThrown)
第一个参数是jqXHR
对象。
同样来自here:
为了向后兼容XMLHttpRequest,jqXHR对象将公开以下属性和方法:
- readyState的
- 状态
- statusText responseXML和/或responseText时的底层请求 用xml和/或文本分别响应setRequestHeader(name, 通过将旧值替换为标准而偏离标准的值) 新的,而不是将新值连接到旧值
- getAllResponseHeaders()
- getResponseHeader()
- statusCode()
- 中止()
如您所见,没有jqXHR.message
属性。所以当你这样做时:
error: function(log) {
console.log(log.message);
}
当然,您将获得未定义的通知,因为该属性不存在。
从this answer,获取您需要执行的错误消息:
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
答案 2 :(得分:0)
使用jquery 1.12.3
为我工作success: function(result) {
alert(result);
},
//显示“test,passing”
下一行JSON在控制台日志中返回: JSON.parse:JSON数据第1行第1列的意外关键字
答案 3 :(得分:0)
似乎错误与json_encode函数有关。
CentOS 5 php安装不包含json.so模块,因此必须手动安装,然后修复错误。
感谢大家的帮助,但非常感谢
答案 4 :(得分:-1)
试试这个:
$(document).ready(function() {
$('#butt_example').on('click', function() {
$.ajax({
url : 'scripts/functions.php',
type : 'GET',
dataType : 'json',
data : 'action=test',
success: function(result) {
var la_result = JSON.parse(result);
console.log(la_result);
},
error: function(log) {
console.log(log.message);
}
});
});
});