我不喜欢使用库,除非我绝对需要。我更喜欢使用原生JavaScript,因为我认为它会做我想要的事情,而且我会更清楚自己在做什么。所以,我想通过AJAX进行一个简单的添加记录操作:
function addToBlacklist() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'api.php?action=addToBlackList');
var jsonObj;
xhr.onreadystatechange = function () {
try {
jsonObj = JSON.parse(xhr.responseText);
} catch (e) {
alert(e.toString());
}
if (jsonObj.status_code === 200) {
alert('Added');
//Add the new word to the end of the list in the grid view
} else {
alert('Add failed');
}
}
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('blackword=' + encodeURIComponent(document.getElementById('blackword')));
}
在服务器端,我以如下方式处理请求(已在页面顶部使用header('Content-Type: application/json')设置了头部):
if(isset($_GET['action'])){
$action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_URL);
switch('action'){
case 'addToBlacklist':
error_log('Action: ' . 'addToBlackList');
$blackword = filter_input(INPUT_POST, 'blackword', FILTER_SANITIZE_URL);
if(file_put_contents(BLACKLIST_FILE, $blackword . PHP_EOL, FILE_APPEND)){
echo json_encode(['status_code'=>200, 'description'=>Translate::get('Adding to blacklist successful')]);
}
else {
echo json_encode(['status_code'=>500, 'description'=> Translate::get('Adding to blacklist failed')]);
}
break;
}
}
问题在于我总是在浏览器中收到这个错误提示:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
xhr.responseText
时,它的值是多少? - Seanvm