无法使用jquery post()发布变量 [英] Unable to post variables with jquery post()

查看:84
本文介绍了无法使用jquery post()发布变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将变量从模态形式传递到另一页.我在表单中使用每个选项的id标签声明变量.

I am trying to pass variables from a modal form to another page. I declare the variables from the form with the id tags in each selection.

页面重新加载到test.php,但是无法回显任何变量.

Page reloads to test.php, however no variable can be echoed.

javascript

javascript

var id = $( "#id" ),
    name = $( "#name" )

$.post("jqtest/test.php", { device_id: "id", device_name: "name" });
load('jqtest/test.php');

test.php

echo $_POST['device_name'];
echo $_POST['device_id'];

推荐答案

这似乎有很多问题...看来您正在使用echo $_POST['device_name'];echo $_POST['device_id'];只是为了确保您的AJAX工作正常.如果是这种情况,则无需使用.load();.您还将发送$( "#id" )$( "#name" )的jQuery对象,而不是这些表单元素中的值.稍后,在您的.post请求中,您将那些相同的变量用引号引起来,这将发送字符串"id"和"name".再说一遍-可能不是您要找的东西.

It looks like there's a lot wrong with this... It looks like you are using echo $_POST['device_name']; and echo $_POST['device_id']; just to ensure that your AJAX is working. If that's the case, you don't need to be using .load();. You are also sending the jQuery object of $( "#id" ) and $( "#name" ) instead of the values within those form elements. Later, in your .post request, you have those same variables in quotes, which is sending the strings "id" and "name". Again - likely not what you're looking for.

您的问题有些复杂,但我会尽力回答.试试这个JS:

Your question is a bit convoluted but I'll do my best to answer. Try this JS:

var id = $("#id").val(),
    name = $("#name").val();

$.post("jqtest/test.php", { device_id: id, device_name: name }, function(response) {
    console.log(response);
});

在您的PHP文件中,使用以下代码:

In your PHP file, use this code:

echo $_POST['device_name'];
echo $_POST['device_id'];

您将看到您的变量显示在浏览器的JS控制台中.使用此脚本,您已通过POST将两个变量发送到test.php,并且test.php将回显结果.添加到$ .post请求中的回调函数将在javascript控制台中显示test.php的输出.在 jQuery文档上了解有关.$post()的更多信息.

You will see your variables show up in the JS console of your browser. With this script, you've sent your two variables to test.php via POST and test.php will echo the results. The callback function added to the $.post request will display the output from test.php in the javascript console. Learn more about .$post() on the jQuery docs.

这篇关于无法使用jquery post()发布变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆