【发布时间】:2018-11-15 07:44:59
【问题描述】:
我讨厌使用库,除非我绝对需要它们。我更喜欢使用 vanilla 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 好像是空的!
-
你在使用 CORS 吗?
-
@SayedMohdAli,是的,js 文件在我发送请求的同一台服务器上运行。有问题吗?
标签: javascript php ajax