简体   繁体   English

从javascript使用get方法访问php时未定义值

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

I want to send value with get method to my php file. 我想使用get方法将值发送到我的php文件。 if i set my url like this 如果我这样设置我的网址

http://example.com?id=13

it can run normally, but when my id is like this 它可以正常运行,但是当我的id是这样时

http://example.com?id=a0013

a get error in my console log a0013 is not defined. 未定义控制台日志a0013中的获取错误。 This is my code 这是我的代码

<?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>

my example.php 我的example.php

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

You seem to be confusing PHP and JavaScript; 您似乎对PHP和JavaScript感到困惑。
PHP is a server side scripting language PHP是服务器端脚本语言
JavaScript is a client side scripting language JavaScript是一种客户端脚本语言

The console you mention, is through a browsers inspector tool, and runs off of JavaScript. 您提到的控制台是通过浏览器检查器工具运行的,并使用了JavaScript。
If you want to get a request param from this, you could do the following; 如果要从中获取请求参数,可以执行以下操作;

// 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])
}

This will output something such as; 这将输出诸如:

Request Param; id = a0013

You can also use these in PHP; 您也可以在PHP中使用它们。

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

Which will result in the same thing. 这将导致相同的结果。 If you wanted just the a0013 value; 如果只需要a0013值; using; 使用

print $_REQUEST['id'];

Will give you this. 会给你这个。
Trying to target via the a0013 won't work as that is the value in the data, not the key 尝试通过a0013定位是无效的,因为那是数据中的值,而不是键

NB - I use $_REQUEST in this, there is also $_GET (what you see in the URL bar and what JavaScript has access to via window.location.search) and $_POST which is hidden from the user 注意 :我在其中使用$ _REQUEST,还有$ _GET(您在URL栏中看到的内容以及JavaScript通过window.location.search可以访问的内容)和$ _POST对用户隐藏

FOLLOWING OP EDIT 跟随操作编辑
Add quote marks around your $id=a001; $id=a001;周围加上引号$id=a001; to make it $id='a001'; 使它成为$id='a001';

The reason it works with 13 and not a0013 (or a001) is because 13 is an integer and does not need quotes, because the latter has a string (starts with "a") it MUST have quotes around it (single or double, doesn't matter) 它与13而不是a0013(或a001)一起使用的原因是因为13是整数并且不需要引号,因为后者具有字符串(以“ a”开头),因此必须在其周围加上引号(单引号或双引号,没关系)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM