Ajax'语法错误:意外令牌<' /'xhr.status 200'

时间:2014-07-25 19:19:50

标签: javascript php jquery ajax json

我不断收到错误消息'语法错误:意外令牌<'如果我运行以下ajax请求,则xhr.status为200。考虑到我能够通过电子邮件发送从JavaScript文件传递到php文件的变量,看起来当使用json将数据传回JavaScript文件时会出现问题。

我是ajax的新手,不幸的是我几个小时以来都无法解决这个问题。

JavaScript代码:

var discount ="";
$('#apply_discount').click(function(){
    discount_input = $('#discount_input').val();
    $.ajax({
        type: 'POST',
        url: 'storescripts/discount.php',
        data: {
            discount_input: discount_input,
             },
        cache: false,
        dataType: 'json',
        success: function(data){
            discount = data.discount;
            alert(discount);
        },
         error:function (xhr, ajaxOptions, thrownError){  
            alert(xhr.status);               
            alert(thrownError); 
        }           
    });     

});

php代码:

<?php
include("includes/session_start.php");
include("connect_to_mysql.php"); 
$discount="";
    if (isset($_POST['discount_input'])) {
        $discount_input = $_POST['discount_input'];
        $discount_input = stripslashes($discount_input);
        $discount_input = preg_replace('/\s+/', '', $discount_input);   
        $discount = mysql_query("SELECT discount FROM discount WHERE coupon_name = '$discount_input' LIMIT 1")or die(mysql_error());    
        $discount = mysql_fetch_row($discount);
        $discount = implode('', $discount);
         mail("my@myemail",$discount,"some message","From: test@mysite.com");
         echo json_encode(array('discount' => $discount));
            }   
?>

1 个答案:

答案 0 :(得分:1)

如果你想从PHP返回json,我相信你需要在PHP文件或ajax调用中指定contentType:

在PHP文件中,在echo json_encode之前(...:

header('Content-Type: application/json');

或在ajax调用中,在success属性之前的某处指定contentType:

contentType: 'application/json',