我需要帮助从我的jquery json结果中格式化json返回html。
这是我的HTML代码:
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "testerer"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "test.php",
data: data,
success: function(data) {
$(".the-return").html(data["json"]);
}
});
return false;
});
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="test.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="testerer" value="" placeholder="Favorite restaurant" />
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="the-return"></div>
&#13;
这是我的test.php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "testerer": testerer(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function udemy(){
$courseid = $_POST['testerer'];
$client_id = 'xxx';
$client_secret = 'xxxxx';
// set HTTP header
$headers = array(
"Authorization: Basic " . base64_encode($client_id . ":" . $client_secret),
"Content-Type: application/vnd.api+json"
);
$url = 'https://xxx/' . $courseid . '/';
// Open connection
$ch = curl_init();
// Set the url, number of GET vars, GET data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$result = curl_exec($ch);
// Close connection
$data["json"] = json_encode($result);
echo json_encode($data, JSON_PRETTY_PRINT);
}
总是得到这样的回报:
"{\"_class\": \"course\", \"id\": 5816, \"title\": \"XXx xxx xxx\", \"url\": \"\/xxx-xxx\/\",
我需要结果可读。
答案 0 :(得分:0)
目前尚不清楚$data
应该包含哪些内容,但问题是您在同一数据上调用了json_encode()
两次:
$data["json"] = json_encode($result);
echo json_encode($data, JSON_PRETTY_PRINT);
答案 1 :(得分:0)
将JSON数据转换为字符串
JSON.stringify(data["json"])
添加如下
$(".the-return").html(JSON.stringify(data["json"]));