试图动态地将字符串发布到PHP

时间:2017-05-31 11:34:08

标签: javascript php forms post dynamic

仅使用JavaScript我想将一个字符串POST到php文件并同时重定向到它,但是,我的php文件没有提取信息。

JavaScript的:

    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代码很简单(这里没有错误,只是为了方便):

$id = $_POST['id'];

编辑:

问题是PHP文件没有提取名称“id”。 php文件中没有问题或我如何构建数据。

2 个答案:

答案 0 :(得分:2)

你犯了一个小错字。虽然这是一个很大的问题。在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);
?>

修改

确保obj.id不为空

答案 1 :(得分:1)

那不是你传递数据的方式。 value是表单输入元素的属性,而不是表单本身。

删除行form.value = data;并替换为

var input = document.createElement('input');
input.type = 'hidden';
input.name = 'id';
input.value = obj.id;
form.appendChild(input);

现在你应该可以获得$_POST['id']