[英]Uncaught SyntaxError: Unexpected token : in WeatherUnderground response
[英]Parsing PHP response: Uncaught SyntaxError: Unexpected token <
我正在使用AJAX來調用PHP腳本。 我需要從響應中解析的唯一一件事是腳本生成的隨機ID。 問題在於PHP腳本引發了許多錯誤。 該錯誤實際上很好,並且不會妨礙程序功能。 唯一的問題是當我跑步時
$.parseJSON(response)
我得到:
Uncaught SyntaxError: Unexpected token <
由於PHP響應以錯誤開頭:
<br />
<b>Warning</b>:
我想知道如何更改PHP或JS,以便即使有錯誤也可以解析ID。
PHP:
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
...
JS:
function returnReport(response) {
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
我知道警告應該得到解決,但是警告對於現在來說功能並不重要,更重要的是
1)即使這些警告已解決,也可能會出現新的警告,並且仍應正確解析JSON並
2)除警告外,還有引起相同問題的“注意”。
為什么不處理並消除警告,使服務器的結果實際上是JSON?
有幾種方法可以解決此問題(任何一種都可以):
1.修正警告。 :
PHP之所以說是出於某種原因。
2.關閉錯誤報告和錯誤顯示 :
在文件頂部放置以下內容
error_reporting(false);
ini_set('display_errors', false);<br/>
3.使用輸出緩沖區 :
在文件頂部
ob_start();
當您擁有數據數組並准備好回顯到瀏覽器時,請清除所有通知警告等的緩沖區。
ob_clean();
echo json_encode($returnData);
ob_flush();
4.設置自定義錯誤處理程序 :
set_error_handler("myCustomErrorHandler");
function myCustomErrorHandler($errno, $errstr, $errfile, $errline){
//handle error via log-to-file etc.
return true; //Don't execute PHP internal error handler
}
5.(可選)在JavaScript中:
整理您的響應,使其成為JSON數組:
function returnReport(response) {
response = response.substring(response.indexOf("{") - 1); //pull out all data before the start of the json array
response = response.substring(0, response.lastIndexOf("}") + 1); //pull out all data after the end of the json array
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}
就像其他人都說過的那樣,您應該真正解決您的錯誤並相應地進行處理。
在您將無法控制但又想相應地處理錯誤的情況下,這是更多的事情:
<?php
//Change it to 'production' or something like that
//so that you don't send debug data on production
define('ENVIRONMENT', 'testing');
//Set your error handler globally
set_error_handler('handle_error');
function handle_error($errno, $errstr, $errfile, $errline, array $errcontext )
{
//Set your headers to send a different than 200 so you can
//catch it on error on jQuery
header($_SERVER["SERVER_PROTOCOL"].' 500 Internal Server Error');
//Set output as json
header('Content-Type: application/json');
//Create some sort of response object
$response = new stdClass;
$response->message = "Application error details";
//You dont want to give debug details unless you are not on prod
if(ENVIRONMENT == 'testing') {
$severity = get_err_severity($errno);
$response->error_detail = "({$severity}) [{$errfile}@L{$errline}]: {$errstr}";
$response->context_vars = $errcontext;
}
//Return the json encoded error detail and exit script
$json = json_encode($response);
exit($json);
}
function get_err_severity($severity)
{
switch($severity) {
case E_ERROR:
return 'E_ERROR';
case E_WARNING:
return 'E_WARNING';
case E_PARSE:
return 'E_PARSE';
case E_NOTICE:
return 'E_NOTICE';
case E_CORE_ERROR:
return 'E_CORE_ERROR';
case E_CORE_WARNING:
return 'E_CORE_WARNING';
case E_COMPILE_ERROR:
return 'E_COMPILE_ERROR';
case E_COMPILE_WARNING:
return 'E_COMPILE_WARNING';
case E_USER_ERROR:
return 'E_USER_ERROR';
case E_USER_WARNING:
return 'E_USER_WARNING';
case E_USER_NOTICE:
return 'E_USER_NOTICE';
case E_STRICT:
return 'E_STRICT';
case E_RECOVERABLE_ERROR:
return 'E_RECOVERABLE_ERROR';
case E_DEPRECATED:
return 'E_DEPRECATED';
case E_USER_DEPRECATED:
return 'E_USER_DEPRECATED';
}
}
function test_error()
{
$test = array('foo'=>'bar');
$baz = $test['baz'];
echo $baz;
}
test_error();
雖然這不能解決更廣泛的警告問題,但我使用此技巧來解析響應:
function returnReport(response) {
var pdfID = parseID(response);
...
}
function parseID(response) {
var responseIndex = response.indexOf('{"id');
var start = responseIndex + 7;
var pdfID = response.slice(start, start + 6);
return pdfID;
}
我知道每個人都建議您修復錯誤,我同意,但是如果您不想這樣做,那么還有另一種解決方案。
如果您收到大量警告,並希望出現新的警告,只需禁用警告和通知的報告即可:
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
如果啟用了ob
ob_end_clean();
ob_start();
echo json_encode($returnData);
或者,在文件頂部
error_reporting(0);
我確信由於即將到來的錯誤,您的PHP代碼中會有一些錯誤,請檢查以下幾件事:
echo
或print
來進行打印響應。 我說這是因為我已經嘗試過您的代碼,並且對我來說工作正常,您還可以檢查一下:
PHP文件:myContentPage.php
<?php
$returnData = array();
$returnData['id'] = 123;
echo json_encode($returnData);
?>
HTML檔案:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.js'></script>
</head>
<body>
<h1>Demo Example</h1>
<script>
function loadResponse() {
var dataString={};
$.ajax({
url:"myContentPage.php",
type: 'POST',
cache:false,
data: dataString,
beforeSend: function() {},
timeout:10000000,
error: function() { },
success: function(response) {
var parsedResponse = $.parseJSON(response);
pdfID = parsedResponse['id'];
console.log(pdfID);
alert(pdfID);
}
});
}
loadResponse();
</script>
</body>
</html>
為了處理警告,您可以執行以下操作:
要跳過警告消息,您可以使用以下方法:
error_reporting(E_ERROR | E_PARSE);
快樂編碼!
在Ajax調用中使用的腳本必須具有完美的構造,不應只是為了方便而引發任何警告,對於生產,您應該禁用erros,因此將其修復到開發中,並使用phps givin的警告來編輯問題,我們將直接為您提供幫助重點。
第一種選擇:
解決引起警告的問題。 一個好的PHP系統永遠不要顯示PHP通知,警告或錯誤。 這可能會暴露一些關鍵信息。
第二種選擇:
只需通過設置禁用錯誤報告
error_reporting(0);
這將起作用,但甚至會向您隱藏任何錯誤。
第三種選擇:
設置一個處理錯誤的錯誤處理函數,並顯示不會造成任何麻煩的JSON友好錯誤消息。
另外,我建議您記錄此異常。 它將允許您調試任何系統故障。
我的推薦?
一起使用第一種和第三種替代品,並保持快樂!
您可以在javascript函數代碼中使用Try..Catch構造,如下所示。
function returnReport(response) {
try
{
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}
catch(err)
{
//Do something with the err
}
}
即使您的php代碼生成調試信息作為響應,此方法也將起作用。
如果要查看JavaScript中的錯誤,則應使用“ try catch”和“ catch”處理PHP上的錯誤,以執行類似“ echo json_enconde($ error);”的操作。 通過這種方式,您可以從JavaScript進行解析。
例:
try{
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
}catch (Exception $e) {
echo json_encode($e);
}
我希望這有幫助 :)!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.