【发布时间】:2020-03-31 13:45:14
【问题描述】:
我从 Ajax 开始,不幸的是我遇到了 JSON.parse() 的问题。我想通过点击传递一个变量。
到目前为止,我还没有找到具体问题的答案。也许这里有人可以帮助我。
错误信息:
Uncaught SyntaxError: Unexpected token < in JSON at position 68
at JSON.parse (<anonymous>)
at Object.<anonymous> (ajax.js?ver=5.3.2:13)
at c (jquery.js:2)
at Object.fireWith [as resolveWith] (jquery.js:2)
at l (jquery.js:2)
at XMLHttpRequest.<anonymous> (jquery.js:2)
我的 JS 函数:/admin/script/ajax.js
$("#make").change(function(){
var make = $('#make').val();
console.log('Select Value hat sich geändert zu ' + make);
$.ajax({
url: wpAjax.ajaxUrl,
data: 'make=' + make,
type: 'post'
}).done(function(model){
model = JSON.parse(model); // Here comes the error.
})
})
})
我的 PHP 函数:admin/script/filter.php
<?php
if(isset($_POST['make'])) {
$model = 'Model S';
echo json_encode($model);
}
?>
主题中的Wordpress functions.php
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/admin/script/ajax.js', array('jquery') );
wp_localize_script( 'ajax-script', 'wpAjax',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
get_template_part( 'admin/script/filter');
【问题讨论】:
-
使用
console.log(model);检查来自脚本的响应,或检查开发者控制台的网络选项卡。您没有从服务器获得正确的 JSON。可能是错误或其他原因。 -
您的 JSON 实际上是干净的 JSON 吗?你的 JSON 是空的吗?
-
console.log(model) 先看初始数据;以及您需要如何处理它,您可能不需要进行解析
-
@emilioestevez — 它当然不是空的。它在第 68 位有一个
<。 -
请显示完整的php代码。它似乎发送了冗余数据作为响应