无法解析返回的JSON字符串,因为它将数据类型添加到JSON字符串中

时间:2018-10-29 05:20:01

标签: javascript json parsing

我有一个基本的AJAX函数,该函数调用PHP脚本,并且该脚本返回了 perfect JSON字符串,我已经检查了它。

这是AJAX代码的样子:

function onLoad() {
    $.ajax({
        url: "php/api.php",
        data: {symbol: "MSFT"},
        async: true, 
        dataType: 'text',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        success:  function (data) {
            console.log("data is: "); 
            console.log(JSON.parse(data)); 
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log("There was an error");
                console.log(thrownError);
            }
    }); 
}

这是php代码的样子:

<?php 

error_reporting(0);

$symbol =$_GET['symbol'];

$data = array("year" => 2018);
$data_string = json_encode($data);


function grabHTML($function_host_name, $url)
{

$ch = curl_init();
$header=array('GET /1575051 HTTP/1.1',
    "Host: $function_host_name",
    'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language:en-US,en;q=0.8',
    'Cache-Control:max-age=0',
    'Connection:keep-alive',
    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4)         
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
    );

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 300);
    curl_setopt( $ch, CURLOPT_COOKIESESSION, true );

    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

    curl_setopt($ch,CURLOPT_COOKIEFILE,'cookies.txt');
    curl_setopt($ch,CURLOPT_COOKIEJAR,'cookies.txt');
    curl_setopt($ch,CURLOPT_HTTPHEADER,$header);

    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_STDERR,$f = fopen(__DIR__ . "/error.log", "w+"));


    $returnHTML = curl_exec($ch); 

if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
}   
   curl_close($ch);
    return $returnHTML; 

} // end of function grabHTML

$url = "https://newsapi.org/v2/everything?q=" . $symbol . "&from=2018-10-29&sortBy=publishedAt&apiKey=0cc1ee750c69497899f81b14d32dfbf9";

$results = grabHTML("newsapi.org", $url);

echo $results;

但是,在前端,数据类型预先添加到JSON字符串中,即

string(17484) " (perfect JSON string here) " 

因此,另一个“”将附加到数据的末尾。这会使JSON.parse()函数崩溃。

我尝试了所有“ dataType:'文本'”,“ dataType:'html'”和“ dataType: 'json'”,并且每次仍会添加数据类型。

我需要阻止它添加数据类型。

布伦特。

1 个答案:

答案 0 :(得分:0)

解决方案是设置     curl_setopt($ ch,CURLOPT_VERBOSE,false); 在PHP脚本中。