5 回答

TA貢獻1862條經驗 獲得超6個贊
為此,我個人要感謝兩個人,他們是:
Nijeesh Joshy用于排序的最大問題 METHOD to METHOD 與 PHP 腳本的矛盾。
布拉德解釋了正確的格式以使操作順利運行
調查結果:為了使這項工作正常工作,即$_POST工作 POST 方法,您需要在 header 中發送 application/x-www-form-urlencoded Content-Type。我不知道,但在 Content-Type 中發送數據是application/json行不通的。
解決方案:
1. SyntaxError: Unexpected token N =>這樣做是因為在 PHP 腳本中,它必須在 中返回json_encode(),這就是為什么它No phone number found, N at 0th position在 else 腳本中的此語句中返回此錯誤。
<?php
include('/Applications/MAMP/htdocs/api/Requests/library/Requests.php');
$request_method = $_SERVER['REQUEST_METHOD'];
if ( $request_method == 'POST' ){
if(isset($_POST['phone_num'])){
echo $_POST['phone_num'];
}else{
echo json_encode('No phone number found');
}
}else {
echo json_encode('No defined function for this method. Please use POST only');
}
?>
2. $_POST 不適用于 Angular 代碼中的 POST 方法 =>已在上面解釋。
import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class AppComponent {
message: string;
url: string = 'xxxxxxx';
customernum: number;
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
body: any = `phone_num=${this.customernum}`;
constructor(private http: HttpClient){}
callMe(){
this.message = 'Please wait....'
this.http.post(this.url, this.body, this.httpOptions).subscribe(
response => console.log(JSON.stringify(response)),
error => console.log(error)
);
}
}
如果您仍然遇到錯誤,那么您的角度代碼中會有一些格式錯誤。請點擊此鏈接。我希望這對你有幫助。我看到人們對使用非常嚴格$_POST[] in place of $_GET[],但這Content-Type就是問題所在。

TA貢獻1842條經驗 獲得超13個贊
SyntaxError: Unexpected token N in JSON 意味著你有一些格式錯誤的 JSON,它通常是一個沒有用引號括起來的字符串。
1) 檢查 this.customernum 是否不為空或不包含任何壞字符。
2) 用雙引號將 phone_num 括起來。

TA貢獻1829條經驗 獲得超9個贊
如果您使用的是表單而不是嘗試直接從該表單添加值,而不是任何額外的變量。用您的表單名稱替換此處的表單
this.http.post(this.url, { 'phone_num': this.form.value.phoneForm}, this.httpOptions).subscribe(
response => console.log(JSON.stringify(response)),
error => console.log(error)
);

TA貢獻1942條經驗 獲得超3個贊
傳遞原始對象{ 'phone_num': this.customernum },不要使用JSON.stringify()
試試這樣:
callMe(){
this.message = 'Please wait....'
this.http.post(this.url, { 'phone_num': this.customernum }, this.httpOptions).subscribe(
response => console.log(JSON.stringify(response)),
error => console.log(error)
);
}
- 5 回答
- 0 關注
- 321 瀏覽
添加回答
舉報