位于0的JSON中出现意外的标记

时间:2018-03-24 06:54:05

标签: php jquery json ajax

我正在使用ajax从输入字段中获取文本并通过php检查它们而不是将它们存储在数据库中...但是在某个地方,某些地方出了问题,我得到Unexpected token s in JSON at position 0这个错误..



$(".d-f-sub").on('click',function(e){
		e.preventDefault();
		resetErrors();
		$('.inputTxtError').children('form input').css({'border-color' : '','box-shadow' : ''});
		var data = {};
		
		 $.each($('form input, form select'), function(i, v) {
              if (v.type !== 'submit') {
                  data[v.name] = v.value;
              }
            });
            
        $.ajax({
            dataType:       "JSON",
            type:           "POST",
            data:           data,
            cache:          false,
            url:            "/ajax/diet/diet-page-error-display.php",
            success:        function(result){   
                if(result === "true"){
                    console.log('raboti do tuk');
                    $(".d-f-sub").submit();
                    window.location = "http://www.homepage.co.uk/thankyou";
                    return false;
                }else {
                   console.log('ne raboti');
                  $.each(result, function(i, v) {
	        //console.log(i + " => " + v); // view in console for error messages
                      var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>';
                      $('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg);
                  });
                  var keys = Object.keys(result);
                  $('input[name="'+keys[0]+'"]').focus();
              }
              return false;
                
            },
    error: function(jqXHR, textStatus, errorThrown) {
        //console.log(JSON.stringify(result));
        alert(jqXHR.status);
        alert(textStatus);
        alert(errorThrown);
    }
        });
        
        
        function resetErrors() {
    $('form input, form select').removeClass('inputTxtError');
    $('label.diet-error').remove();
}
		});
&#13;
<?php
header('Content-type:application/json;charset=utf-8');
    
if(isset($_POST)){
        if (filter_var($_POST['age'], FILTER_VALIDATE_INT) === false){
        	$_SESSION['errors']['age'] = 'Моля използвайте само цифри в полето за Вашата възраст!';
        }
        if (filter_var($_POST['height'], FILTER_VALIDATE_INT) === false){
        	$_SESSION['errors']['height'] = 'Моля използвайте само цифри в полето за Вашата височина!';
        }
        if (filter_var($_POST['weight'], FILTER_VALIDATE_INT) === false){
        	$_SESSION['errors']['weight'] = 'Моля използвайте само цифри в полето за Вашато тегло!';
        }
        if (filter_var($_POST['budget'], FILTER_VALIDATE_INT) === false){
        	$_SESSION['errors']['budget'] = 'Моля използвайте само цифри в полето за Вашият бюджет!';
        }
        if (filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false){
            $_SESSION['errors']['email'] = 'Моля въведете валиден имейл адрес!';
            
        }
        
        
        if(empty($_POST['email'])){
            $_SESSION['errors']['email'] = 'Моля въведете имейл за връзка';
        }
        
        if(empty($_POST['age'])){
        	$_SESSION['errors']['age'] = 'Моля въведете Вашата възраст!';
        }
        if(empty($_POST['height'])){
        	$_SESSION['errors']['height'] = 'Моля въведете Вашата височина!';
        }
        if(empty($_POST['weight'])){
        	$_SESSION['errors']['weight'] = 'Моля въведете Вашето тегло!';
        }
        if(!isset($_POST['sex'])){
        	$_SESSION['errors']['sex'] = 'Моля изберете пол !';
        }
        if(!isset($_POST['activity'])){
        	$_SESSION['errors']['activity'] = 'Моля изберете активност! !';
        	
        }
        if(!isset($_POST['goal'])){
        	$_SESSION['errors']['goal'] = 'Моля изберете цел !';
        }
}//
if(count($_SESSION['errors']) > 0){
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
    {
        
         echo json_encode($_SESSION['errors']);
         unset($_SESSION['errors']);
         exit();
    
    }
        echo "<ul>";
        foreach($_SESSION['errors'] as $key => $value){
        echo "<li>" . $value . "</li>";
        }
        echo "</ul>";
        unset($_SESSION['errors']);
        exit();
}else{
    
    $age            =  clean_xss_int($_POST['age']);
    $height         =  clean_xss_int($_POST['height']);
    $weight         =  clean_xss_int($_POST['weight']);
    $email          =  clean_xss($_POST['email']);
    $sex            =  clean_xss($_POST['sex']);
    $activity       =  clean_xss($_POST['activity']);
    $goal           = clean_xss($_POST['goal']);
    $diseases       =  clean_xss($_POST['diseases']);
    $liked_foods    =  clean_xss($_POST['liked_foods']);
    $hated_foods    =  clean_xss($_POST['hated_foods']);
    $budget         =  clean_xss_int($_POST['budget']);
    $intership      =  clean_xss($_POST['training']);
    $description    =  clean_xss($_POST['eat_usually']);
    
        $data = array(
        'age'       => $age,
        'height'    => $height,
        'weight'    => $weight,
        'email'     => $email,
        'sex'       => $sex,
        'activity'  => $activity,
        'goal'          => $goal,
        'diseases'          => $diseases,
        'liked_foods'          => $liked_foods,
        'hated_foods'          => $hated_foods,
        'budget'          => $budget,
        'intership'          => $intership,
        'description'       =>$description
        );
        
        //Here is the query usually
        
        echo json_encode($data);
        ?>
&#13;
&#13;
&#13;

无论我做什么,总是返回Unexpected token s in JSON at position 0。现在我试图删除DataType: "JSON"使用过的Content-Type标头,使用json_encode()(有JSON的结果)编码)

Link to network response tab

在json之前也尝试过utf8_encode(),但它需要一个字符串而不是数组。 谢谢!

1 个答案:

答案 0 :(得分:0)

好的,所以我整天都在犯这个错误,有适合我的解决方案。

首先,我检查了JSON在www.jsonlint.com中的有效性是否有效。

第二个我的clean_xss_int函数是错误的,如果它是数组,我输入的值就是,因此最终结果是数字字段的字符串和文本字段的数组。

第三个(因为我是ajax的新手)我检查了整个php端,并意识到即使有空字段也必须返回错误或返回数据数组ajax得到它两个成功的操作.Plus没有需要再次将$ data数组传递给json,因为我只需要插入查询。所以我写了一个数组,我在ajax中返回成功,即数组('0'=&gt;'true');我正在使用ajax中的字符串并检查成功是否等于字符串'true'。代码如何显示:

 $.ajax({
            type:           "POST",
            data:           data,
            dataType:       "JSON",
            url:            "/ajax/diet/diet-page-error-display.php",
            success:        function(result){  
                JSON.stringify(result);// <---- new ;d
                if(result == "true"){ <--- comparing with 2 x = instead of 3
                    $(".d-f-sub").submit();
                    window.location = "http://www.musclevale.com/diet";
                    return false;
                }else {
                  $.each(result, function(i, v) {
                      var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>';
                      $('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg);
                  });
                  var keys = Object.keys(result);
                  $('input[name="'+keys[0]+'"]').focus();
              }
              return false;
                
            },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status);
        alert(textStatus);
        alert(errorThrown);
    }
        });
<?php 
   $age            =  clean_xss_int($_POST['age']);
    $height         =  clean_xss_int($_POST['height']);
    $weight         =  clean_xss_int($_POST['weight']);
    $email          =  clean_xss($_POST['email']);
    $sex            =  clean_xss($_POST['sex']);
    $activity       =  clean_xss($_POST['activity']);
    $goal           =  clean_xss($_POST['goal']);
    $diseases       =  clean_xss($_POST['diseases']);
    $liked_foods    =  clean_xss($_POST['liked_foods']);
    $hated_foods    =  clean_xss($_POST['hated_foods']);
    $budget         =  clean_xss_int($_POST['budget']);
    $intership      =  clean_xss($_POST['training']);
    $description    =  clean_xss($_POST['eat_usually']);
    
        $data = array(
        'age'       => $age,
        'height'    => $height,
        'weight'    => $weight,
        'email'     => $email,
        'sex'       => $sex,
        'activity'  => $activity,
        'goal'          => $goal,
        'diseases'          => $diseases,
        'liked_foods'          => $liked_foods,
        'hated_foods'          => $hated_foods,
        'budget'          => $budget,
        'intership'          => $intership,
        'description'       =>$description
        );
         
       $fields = implode(',',array_keys($data));
	    $values = '\''  . implode('\', \'', $data) . '\'';
    $query = mysqli_query($connect,"INSERT INTO buyed_diets ($fields) VALUES ($values)");
    echo json_encode(array('0' => 'true'));// <----new ;d

?>