【发布时间】:2020-06-03 13:30:12
【问题描述】:
我不是 php 开发人员,我这样做是为了帮助朋友。我的 php 文件中的 ajax 响应有问题。在我的 HTML 中,我提出了一个 ajax 请求
function addNewBrand() {
disableAllButton();
var excludeBrandOnFacebook = $('#facebook_brand_excluded').is(":checked");
var excludeBrandOnTrovaprezzi = $('#trovaprezzi_brand_excluded').is(":checked");
if(excludeBrandOnFacebook || excludeBrandOnTrovaprezzi) {
var outOfStockArray = getOutOfStockValueArray();
var categories = getExcludedCategory();
var newBrand = getNewBrandToExclude();
var brands = getExcludedBrand();
brands.push(newBrand);
var obj = { excludeOutOfStock: outOfStockArray, brands: brands, categories: categories};
var rulesJSON = JSON.stringify(obj);
console.log(rulesJSON);
$.ajax({
url: '/save_rules.php',
type: 'POST',
dataType: "json",
data: rulesJSON,
cache: false,
success: function(data) {
if(data.status == 'success'){
appendRow(newBrand);
alert("Complete!");
$( '#brand_to_append').val('');
$( '#trovaprezzi_brand_excluded' ).prop('checked', false);
$( '#facebook_brand_excluded' ).prop('checked', false);
} else if(data.status == 'error'){
alert("An error occours! " + data.msg);
}
enableAllButton();
},
error: function( result ) {
console.log(result);
alert("Ops, something went wrong. " + result.msg);
enableAllButton();
}
});
} else {
enableAllButton();
}
}
并以这种方式在我的save_rules.php中处理
#!/usr/bin/php
<?php
if( session_status() != PHP_SESSION_ACTIVE ){
session_start();
}
//require platform core files
require_once ($_SERVER['DOCUMENT_ROOT'] . "/wp-load.php");
require_once ($_SERVER['DOCUMENT_ROOT'] . "/wp-includes/pluggable.php");
//include(ABSPATH . "wp-includes/pluggable.php");
ini_set("memory_limit", '2048M');
header('Content-type: application/json');
$rawdata = file_get_contents("php://input");
// Let's say we got JSON
$decoded = json_decode($rawdata);
$file = $_SERVER['DOCUMENT_ROOT']. "/rules.json";
$jsonFile = fopen( $file, "w+" );
fwrite($jsonFile, $rawdata);
fclose($jsonFile);
$post_array = array();
if( $rawdata != null ) {
$post_array[] = ['code'=>200, 'status'=>'success'];
} else {
$post_array[] = ['code'=>400, 'status'=>'error'];
}
echo json_decode( $post_array );
?>
直到几天前一切正常,但现在我遇到了错误。实际上我收到了 200 状态代码响应,但是在我的 js 函数中,错误部分被触发而不是成功。我认为问题出在我的 JSON 响应上。我检查了 chrome 控制台,我从服务器上得到了这个
#!/usr/bin/php
{"code":200,"status":"success"}
为什么会这样?为什么直到几天前才发生这种情况?我们将不胜感激。
【问题讨论】:
-
删除 php 文件的第一行。
-
你检查了实际的返回字符串吗?它仍然是有效的 JSON。有时琴弦会被切断。
-
@RST 如何检查返回字符串?
-
@fredrik 我将尝试删除第一行。但是要知道,php文件的第一行是不是必须的?
-
print_r() 或 var_dump() $rawdata 之前的解码命令?
标签: javascript php ajax