简体   繁体   English

JSON中位于位置0的意外令牌

[英]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检查它们而不是将它们存储在数据库中...但是在行上的某个地方,出了点问题,并且我Unexpected token s in JSON at position 0收到了Unexpected token s in JSON at position 0这个错误。 。

 $(".df-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'); $(".df-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) 无论我做什么,总是Unexpected token s in JSON at position 0返回Unexpected token s in JSON at position 0 。现在,我尝试删除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. 在json之前也尝试过utf8_encode(),但是它需要一个字符串而不是数组。 Thank you! 谢谢!

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 aka 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. 第三(因为我是ajax的新手),我检查了整个php端,并意识到即使存在空字段,aka也必须返回错误或返回数据数组ajax才能成功完成操作。此外,不需要传递$ data数组再次转换为json,因为我只需要用于插入查询。 So i wrote array which i am returning as success in ajax which is array('0' => 'true'); 所以我写了我在ajax中作为成功返回的array(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中将其设置为字符串,并检查成功是否等于字符串'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 $(".df-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 ?> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM