2017-09-26 23 views
1

AgnularJS版本意外的字符是v1.5.6JSON.parse:在AngularJS和PHP

當用戶輸入數據並提交表單數據將使用PHP是商店中的MySQL。但我得到錯誤< JSON.parse:意外的字符>在Firefox中。

在我DB_formSave.php

,我有整個代碼,比如創建表..插入查詢..但首先,我要確保它的連接數據庫,並angularJS

另外,誰能告訴我PHP不僅可以aceept JSON格式或對象?而AngulrJS只能挑戰JSON或Object?我很新,所以請把你的知識分享給我。

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"; 

?> 
+0

是它節省你的錯誤或 –

+0

之前,它是保存後,並得到錯誤 – Jason

回答

0

你可以在你嘗試一下PHP了對JSON解碼。

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

我試過之後,但我還是錯誤 – Jason

+0

我sloved我剛好低於行頭刪除2(「訪問控制允許來源:* 「); header(「Content-Type:application/json; charset = UTF-8」);任何人都可以解釋它的作用? – Jason

0

我sloved我正下方行中刪除2

標題( 「訪問控制允許來源:*」); header(「Content-Type:application/json; charset = UTF-8」);

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