簡體   English   中英

從javascript使用get方法訪問php時未定義值

[英]value not defined when access php with get method from javascript

我想使用get方法將值發送到我的php文件。 如果我這樣設置我的網址

http://example.com?id=13

它可以正常運行,但是當我的id是這樣時

http://example.com?id=a0013

未定義控制台日志a0013中的獲取錯誤。 這是我的代碼

<?php
//set $id value
$id=a001;
?>
<script type='text/javascript'> 
function init(){
     ja = new google.maps.Data();
     ja.loadGeoJson('example.php?id='+<?php echo $id; ?>+'');
}
</script>

我的example.php

<?php
$id=$_GET['id'];
//another action
?>

您似乎對PHP和JavaScript感到困惑。
PHP是服務器端腳本語言
JavaScript是一種客戶端腳本語言

您提到的控制台是通過瀏覽器檢查器工具運行的,並使用了JavaScript。
如果要從中獲取請求參數,可以執行以下操作;

// Remove the "?" from the URL and split this down by the ampersand
var requestParams = window.location.search.replace("?", "").split("&");
for (var i in requestParams)
{
    // For each of the request parts, split this by the = to het key and value
    // the console log them to display
    var _params = requestParams[i].split("=");
    console.log("Request Param; " + _params[0] + " = " + _params[1])
}

這將輸出諸如:

Request Param; id = a0013

您也可以在PHP中使用它們。

foreach ($_REQUEST as $key => $value)
{
    print "Request Param; {$key} = {$value}<br />";
}

這將導致相同的結果。 如果只需要a0013值; 使用

print $_REQUEST['id'];

會給你這個。
嘗試通過a0013定位是無效的,因為那是數據中的值,而不是鍵

注意 :我在其中使用$ _REQUEST,還有$ _GET(您在URL欄中看到的內容以及JavaScript通過window.location.search可以訪問的內容)和$ _POST對用戶隱藏

跟隨操作編輯
$id=a001;周圍加上引號$id=a001; 使它成為$id='a001';

它與13而不是a0013(或a001)一起使用的原因是因為13是整數並且不需要引號,因為后者具有字符串(以“ a”開頭),因此必須在其周圍加上引號(單引號或雙引號,沒關系)

暫無
暫無

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

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