在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

?>


注意!

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



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