Javascript 尝试将字符串动态发布到PHP
仅使用JavaScript,我想将字符串发布到php文件,同时重定向到该文件,但是,我的php文件没有获取信息 JavaScript:Javascript 尝试将字符串动态发布到PHP,javascript,php,forms,post,dynamic,Javascript,Php,Forms,Post,Dynamic,仅使用JavaScript,我想将字符串发布到php文件,同时重定向到该文件,但是,我的php文件没有获取信息 JavaScript: var data = "&id=" + obj.id; var redirect = function(url, method) { var form = document.createElement('form'); form.method = method; form.action =
var data = "&id=" + obj.id;
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
form.value = data;
document.body.appendChild(form);
form.submit();
};
redirect("summary.php","POST");
PHP代码很简单(这里没有错误,只是为了方便):
编辑:
问题是PHP文件没有选择名称“id”。php文件或我如何构造数据都没有问题。您输入了一个小错误。尽管这是一个巨大的问题。在PHP中,使用
$
符号创建变量
var data = "id=" + obj.id;//you don't necessarilly need the & as you are only passing one item(value)
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
//form.value = data;//this won't work. form does not have value attribute:
//create input element
var i = document.createElement("input");
i.type = "text";//set type.
i.name = "id";//set name of the input
i.id = "id";
i.value = obj.id;//set value of input
form.appendChild(i);//add this input to the form
document.body.appendChild(form);//add the form to the body
form.submit();//dynamically submit
};
redirect("summary.php","POST");
在php脚本中,按如下方式访问它
<?php
error_reporting(E_ALL);//show all errors and notices
$id = $_POST['id'];//you forgot the $ sign
//for debugging, check the post array
print_r($_POST);
?>
编辑:
确保对象id不为空这不是传递数据的方式<代码>值是表单输入元素的属性,而不是表单本身 因此,删除行
form.value=data代码>并替换为
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'id';
input.value = obj.id;
form.appendChild(input);
现在,您应该能够在网络检查器上获得$\u POST['id']
$id
not&id
,您是否看到变量id带有值?我可以向您保证,这不是问题。只是因为我把它打出来了。它已在原始文件中修复。你的控制台怎么说?控制台说它找不到正确名称为“id”的对象。但我找到了解决办法。稍后将发布。我添加了一个解决方案。你也可以看看,这给了我解决方案,虽然我自己也找到了,但我就是这样做的。
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'id';
input.value = obj.id;
form.appendChild(input);