2014-09-24 22 views
0

我有问题。从PHP返回到我的ajax调用时出现错误。jQuery ajax - SyntaxError:JSON.parse与罚款json

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 

在PHP我这样做

echo json_encode(array("message1" => "Hi","message2" => "Something else")); 

我Ajax调用

$.ajax({ 
     type: "POST", 
     url: "s_save.php", 
     data: data, 
     cache: false, 
     dataType: "json", 
     beforeSend: function() { 
      console.log("beforesend: "+data); 
     }, 
     success: function(){ 
      console.log("form search in db: "+data); 
      sendMail(mailName,mailAdress, customertype); 
     }, 
      error: function (xhr, ajaxOptions, thrownError) { 
      console.log(xhr.status); 
      console.log(thrownError); 
      console.log(ajaxOptions) 
      } 
    }); 
} 

现在,如果我在我的萤火看我一看便知,有什么对我来说很好。

{"message1":"Hi","message2":"Something else"} 

错误部分,但这样说。

200 

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 

parsererror 

我不明白。 JSON返回对我来说看起来很好。为什么我得到错误?

编辑:

我做的PHP文件中的一些变化,第一个答案后,但没有帮助 标题(“内容类型:应用程序/ JSON”);

$output = array("data" => "Hi","message2" => "Something else"); 
$output = str_replace(' ', '', $output); 
echo json_encode($output); 

编辑2

这是修复的问题。谢谢你的帮助!

Save the file as UTF-8 without BOM. – Álvaro G. Vicario 12 mins ago 
+1

你没有使用'data',是吗?您需要将它作为参数传递给成功回调 – 2014-09-24 15:03:14

+0

我认为您必须在PHP页面中为JSON响应设置特定的内容类型。 – Ragnar 2014-09-24 15:03:15

+0

您是否验证过在JSON之前没有输出额外的空格或其他字符? – JAAulde 2014-09-24 15:04:33

回答

0

设置dataType:“html”而不是json。