在0位置的JSON中意外的令牌s。

[英]Unexpected token s in JSON at position 0


I am using ajax to get texts from an input field and check them through php than store them in the database...But somewhere on the line, something is wrong and I am getting Unexpected token s in JSON at position 0 this error...

我使用ajax从输入字段获取文本,并通过php检查它们,而不是将它们存储在数据库中……但是在这条线上的某个地方,有些地方出错了,而我在JSON中得到了意想不到的令牌,这个错误…

$(".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();
}
		});
<?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);
        ?>

No matter what I do it's always returning Unexpected token s in JSON at position 0.For now i have tried to remove DataType: "JSON" used Content-Type header, use json_encode() (there is the result from JSON encode)

无论我做什么,它总是在0位置以JSON的形式返回未预料到的令牌。现在,我已经尝试删除DataType:“JSON”使用Content-Type头,使用json_encode() (JSON编码的结果)

Link to network response tab

链接到网络响应选项卡。

Also tried utf8_encode() before json,but it require a string not array. Thank you!

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

1 个解决方案

#1


0  

OK so i was on this error whole day, there is the solution which worked for me.

我一整天都在犯这个错误,有个办法对我有效。

First i checked if JSON is valid in www.jsonlint.com and it was valid.

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

Second my clean_xss_int function was wrong, i was imploding the input value if it is array, so the end result was strings for number fields and arrays for text fields.

第二,我的clean_xss_int函数是错误的,如果它是数组,我就会将输入值内爆炸,所以最终的结果是为文本字段的数字字段和数组的字符串。

Third (because i am new to ajax) I checked the whole php side, and realized that even if there is empty field a.k.a must return error or return the data array ajax got it both for successful operation.Plus that there is no need to pass the $data array to json again,because i need it only for the insert query. So i wrote array which i am returning as success in ajax which is array('0' => 'true'); And i am making it string in ajax and checking if success is equal to string 'true'.There is how code looks like:

第三(因为我是ajax的新手),我检查了整个php端,并意识到即使有空字段a.k。必须返回错误或返回数据数组ajax,以便成功操作。另外,不需要再次将$data数组传递给json,因为我只需要它用于插入查询。所以我写了一个数组,在ajax中作为成功返回数组('0' => '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

?>

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2018/03/24/7201edd605a53c7fc086878a188a6249.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告