到目前为止我有什么:
我在PHP中有一个包含以下内容的表单:
<input type="submit" id="0" name="0" value="This button">
<input type="submit" id="1" name="1" value="This button">
<input type="hidden" id="response" name="response" value="150">
问题:
我想将响应值与name = 1或name = 0一起发送,具体取决于用户提交的按钮。但是,这应该使用键盘字母A和S来完成。如果用户按下字母A,则应提交值0,如果按下S,则应发送值1.
jQuery代码:
$(document).ready(function()
{
// listens for any navigation keypress activity
$(document).keypress(function(e)
{
switch(e.which)
{
// user presses the "a"
case 97: submitViaKeypress("0");
break;
// user presses the "s" key
case 115: submitViaKeypress("1");
break;
}
});
});
// shows a given element and hides all others
function submitViaKeypress(element_id)
{
var response = $('#response').attr('value');
$.ajax({
type: "POST",
url: "initiate.php",
data: "response=" + response + "&" + element_id + "=" + element_id
});
}
目标:
“initiate.php接收两个POST变量(响应和0或1)。
答案 0 :(得分:0)
你想要做的是:
<form id="key_form" action="initiate.php" method="POST">
<p>Press A or S</p>
<input type="hidden" id="key" name="key" value="">
<input type="hidden" id="response" name="response" value="150">
</form>
并且
$(document).keypress( function( e )
{
if ( e.which == 97 )
{
$("input#key").val( 1 );
$("form#key_form").submit();
} else if (e.which == 115)
{
$("input#key").val( 2 );
$("form#key_form").submit();
}
}
答案 1 :(得分:0)
我不确定这是否会导致jQuery'bork'或者不...但看起来你将POST数据作为GET数据发送。
data: "response=" + $('#response').attr('value') + "&key=" + e.which;
如果您尝试使用$ _POST ['response']在initiate.php中查找这些变量,我想它将无法找到它们,除非jQuery知道将它们神奇地转换为后置变量。
0或1的post变量是否也需要命名为0或1?根据变量的设置更改变量名称有点奇怪。因此,为了本示例的目的,我将更改变量名称为keyPressed。即(keyPressed = 0或keyPressed = 1)。
// shows a given element and hides all others
function submitViaKeypress(element_id)
{
var response = $('#response').attr('value');
$.ajax({
type: "POST",
url: "initiate.php",
data: {response:response, keyPressed: element_id}
});
}
现在在您的initiate.php文件中使用$ _POST变量获取这些变量。
$response = $_POST['response'];
$keyPressed = $_POST['keyPressed'];