簡體   English   中英

JSON.parse:AngularJS和PHP中的意外字符

[英]JSON.parse: unexpected character in AngularJS and PHP

AgnularJS版本為v1.5.6

當用戶輸入數據並提交表單數據時,將使用PHP將其存儲在mySQL中。 但我在Firefox中收到錯誤<JSON.parse:意外字符>。

在我的DB_formSave.php中,我有整個代碼,例如創建表..插入查詢..但是首先,我要確保它是連接數據庫和angularJS

另外,任何人都可以告訴我php只能使用aceept JSON格式或Object? 和AngulrJS只能接受JSON或對象? 我很新,請與我分享您的知識。

controller.js

var userControllers = angular.module('userControllers', []);


userControllers.controller('UserFormController', ['$scope', '$http', 
'$location', '$window', 'myFactory', function ($scope, $http, $location, 
$window, myFactory) {
var dataObj = "";
var config = { headers: { 'Content-Type': 'application/x-www-form urlencoded;charset=utf-8;' } }

$scope.submitForm = function (user) {
    myFactory.set(user);  // Set data to myFactory to share with ConfirmationController        
    dataObj = {
        "name": user.name, 
        "province": user.province, 
        "telephone": user.telephone,
        "postalcode": user.postalcode, 
        "salary": user.salary
    }
    console.log(dataObj);   //it shows this format like below :

      Object { name: "Jason", province: "Québec", telephone: "(416) 123-1234", postalcode: "M2N3L3", salary: "40.000" }

    $http.post('ajax/DB_formSave.php', dataObj)
    .success(function(data) {
        console.log(data);
        console.log(dataObj);
    })
  }

}]);

DB_formSvae.php

<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$post_date = file_get_contents("php://input");
$data = json_decode($post_date);

$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "mydb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// check connection
if($conn->connect_error){
die("Connection failed:".$conn->connect_error);
}
echo "Connected successfully\n";

?>

您可以嘗試使用php進行json解碼。

$post_date = file_get_contents("php://input");
$data = json_decode($post_date, true);

我覺得我只刪除下面兩行

header(“ Access-Control-Allow-Origin:*”); header(“ Content-Type:application / json; charset = UTF-8”);

任何人都可以解釋它的作用嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM