我希望我的响应以JSON对象形式返回。但在一些函数中,它以字符串形式返回,我想要解析它。我该如何实现?这是我的函数。
function serverRequest(requestDATA, successCallback, errorCallback, hideIndicator, showAlert){
var METHOD = "POST";
var serverURL = 'http://istudy.com.pk/api/server.php'; //Path to Server.php
//var serverURL = 'http://localhost/istudy/server.php'; //Path to Server.php
var DATA_TYPE = 'json';
var TIMEOUT = 20000;
console.log(requestDATA);
$$.ajax({
url: serverURL,
data: requestDATA,
dataType: DATA_TYPE,
type: METHOD,
timeout: TIMEOUT,
success: function(data){
successCallback(data, hideIndicator, showAlert);
},
error: function(a, b, c){
errorCallback(a, b, c, hideIndicator, showAlert);
}
});
}
这是我的responseText
responseText: "{"status":"success","message":"Your Order has Processed. Please Note this pin <b style=\"background-color:green;\">osIyKvAp<\/b> and send it to the admin with payment details."}"
这是我的PHP函数
function confirm_order($id, $newarray, $cn) {
$today = date('y-m-d');
$expiry = date('Y-m-d', strtotime("+30 days"));
$total_items = 0;
$total_price = 0;
foreach ($newarray as $key => $val) {
$total_items++;
foreach ($val as $doc) {
$total_price = $total_price + $doc->doc_price;
}
}
$pin = random_string('alnum', 8);
$sql = "INSERT INTO orders (order_id, order_UserId, order_total_items, order_amount, date_created,order_status,order_pin)
VALUES ('', '" . $id . "', '" . $total_items . "', '" . $total_price . "', '" . $today . "','0','" . $pin . "')";
if (mysqli_query($cn, $sql)) {
$order_id = mysqli_insert_id($cn);
foreach ($newarray as $key => $val) {
$total_docs = 0;
$total_items++;
$sep = '|';
$sub_price = 0;
$doc_list = '';
foreach ($val as $doc) {
$doc_list .= $doc->doc_id . $sep;
$sub_price = $sub_price + $doc->doc_price;
$total_docs++;
$sep = '|';
}
$sql = "INSERT INTO cart_items (uc_id, uc_user_id, uc_course_id, uc_course_docs_id, uc_course_docs_num,uc_price,uc_order_num,uc_order_status,uc_dateBuy,uc_dateExpire)
VALUES ('', '" . $id . "', '" . $key . "', '" . $doc_list . "', '" . $total_docs . "','" . $sub_price . "','" . $order_id . "','0','" . $today . "','" . $expiry . "')";
mysqli_query($cn, $sql);
}
$response_array['status'] = 'success';
$response_array['message'] = 'Your Order has Processed. Please Note this pin <b style="background-color:green;">' . $pin . '</b> and send it to the admin with payment details.';
} else {
$response_array['status'] = 'error';
$response_array['message'] = 'An error occurred. Please try again later.';
}
echo json_encode($response_array);
}
如果我的响应是字符串,我可以在 JSON.parse 中放置任何检查吗?
dataType: "json"
时,它会自动将响应解析为 JSON。无需手动操作。 - 4castleecho json_encode($response_array);
,但在此之前你是否确保执行了header('Content-Type:application/json')
? - loretoparisi