语法错误:意外的标记<'/ & # 39; xhr.200 & # 39;状态


Ajax 'Syntax Error: unexpected token <' / 'xhr.status 200'

我一直得到错误消息'语法错误:意外的令牌<'和一个xhr。状态200,如果我运行以下ajax请求。考虑到我能够将自己从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));
            }   
?>

如果您希望从PHP返回json,我认为您需要在PHP文件或ajax调用中指定contentType:

在PHP文件中,在echo json_encode(…:

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

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

contentType: 'application/json',