我想讓用戶輸入一個 URL。我想使用 Ajax 將該 URL 發送到我網站上的另一個頁面。在另一個頁面上,它將 url 存儲在一個變量中,并對 url 做一些事情。問題:如果用戶沒有輸入 URL 而是一些雙引號,我會收到錯誤消息。主頁上的代碼:var url = document.getElementById("url").value;$.ajax({ type: "POST", url: "api/checkURL", processData: false, contentType: "application/json", data: '{"URL": "'+url+'"}', success: function(r) { //do something here }})其他頁面上的代碼(我將 Ajax 請求發送到的頁面)if($_GET['url'] == "checkURL") { $data = file_get_contents("php://input"); $data = json_decode($data); $url = $data->URL; //do something with the url}如果有人輸入雙引號,我得到的錯誤<b>Notice</b>: Trying to get property 'URL' of non-object in <b>C:\xampp\htdocs\website\api\index.php</b> on line <b>15</b><br />(第 15 行是行$url = $data->URL;:)如果用戶輸入https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png,它可以工作并且沒有錯誤。但是,如果用戶輸入",則會出現錯誤。有誰知道我該如何解決這個問題?
1 回答

楊魅力
TA貢獻1811條經驗 獲得超6個贊
用于JSON.stringify創建 JSON,不要手動創建。它將正確地轉義引號。
$.ajax({
type: "POST",
url: "api/checkURL",
processData: false,
contentType: "application/json",
data: JSON.stringify({URL: url}),
success: function(r) {
//do something here
}
})
- 1 回答
- 0 關注
- 123 瀏覽
添加回答
舉報
0/150
提交
取消