简体   繁体   English

格式化html返回json

[英]formating return json in html

I need help formatting json return in html from my jquery json result. 我需要格式化jquery json结果中的html返回的json返回格式的帮助。

this my html code : 这是我的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> 

and this my test.php 这是我的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);
}

always got return like this : 总是得到这样的回报:

"{\"_class\": \"course\", \"id\": 5816, \"title\": \"XXx xxx xxx\", \"url\": \"\/xxx-xxx\/\",

I need result readable. 我需要可读的结果。

It's not clear what your $data should contain, but it looks like the problem is that you're calling json_encode() twice on the same data: 目前尚不清楚$data应该包含什么,但问题似乎是您在同一数据上两次调用json_encode()

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

Convert JSON data into string 将JSON数据转换为字符串

JSON.stringify(data["json"])

add as below 添加如下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM