簡體   English   中英

格式化html返回json

[英]formating return json in html

我需要格式化jquery json結果中的html返回的json返回格式的幫助。

這是我的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> 

這是我的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\/\",

我需要可讀的結果。

目前尚不清楚$data應該包含什么,但問題似乎是您在同一數據上兩次調用json_encode()

$data["json"] = json_encode($result);
echo json_encode($data, JSON_PRETTY_PRINT);

將JSON數據轉換為字符串

JSON.stringify(data["json"])

添加如下

$(".the-return").html(JSON.stringify(data["json"]));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM