我使用以下代码检测“enter”键并将文本输入的值发送到php页面:
$(document).ready(LoadMe);
function LoadMe()
{
$('#test').bind('keypress', function(e){
var code = e.keyCode ? e.keyCode : e.which;
if(code == 13) // Enter key is pressed
{
var theval = $(this).val();
var sessName = '<?php echo $_SESSION['username']?>';
//alert(theval);
$('<p>'+sessName+': '+theval+'</p>').appendTo('#content');
}
$.ajax({
type: "GET",
url: "savechat.php?msg="+theval,
//data: { value : theval },
success: function(data)
{
//alert("success!");
}
});
});
}
savechat.php
// echo $_GET['msg'];
$file = 'people.txt';
$current = file_get_contents($file);
$current .= $_GET['msg']."\n";
file_put_contents($file, $current);
HTML:
<input id="test" type="text" >
<div id="content"> </div>
事件虽然代码有点混乱但它有效,但txt文件会更新很多未定义的行:
undefined
undefined
1
undefined
12
undefined
123
1234
undefined
123456
1234566
12345667
123456678
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
r
感谢您的宝贵意见。
答案 0 :(得分:1)
问题是如果不是代码13(= Enter),你就会触发ajax事件。
theval
仅定义如果您点击输入(代码13) - 否则为undefined
;-)。将其更改为:
$(document).ready(LoadMe);
function LoadMe()
{
$('#test').bind('keypress', function(e){
var code = e.keyCode ? e.keyCode : e.which;
if(code == 13) // Enter key is pressed
{
var theval = $(this).val();
var sessName = '<?php echo $_SESSION['username']?>';
//alert(theval);
$('<p>'+sessName+': '+theval+'</p>').appendTo('#content');
$.ajax({
type: "GET",
url: "savechat.php?msg="+theval,
//data: { value : theval },
success: function(data)
{
//alert("success!");
}
});
}
});
}
它应该可以正常工作;-)) - 虽然未经测试......
答案 1 :(得分:1)
尝试使用enter key
中的ajax代码
if(code == 13) // Enter key is pressed
{
var theval = $(this).val();
var sessName = '<?php echo $_SESSION['username']?>';
//alert(theval);
$('<p>'+sessName+': '+theval+'</p>').appendTo('#content');
$.ajax({
type: "GET",
url: "savechat.php?msg="+theval,
//data: { value : theval },
success: function(data)
{
//alert("success!");
}
});
}
答案 2 :(得分:0)
Try this
$(document).ready(LoadMe);
function LoadMe()
{
$('#test').bind('keypress', function(e){
var code = e.keyCode ? e.keyCode : e.which;
if(code == 13) // Enter key is pressed
{
var theval = $(this).val();
var sessName = '<?php echo $_SESSION['username']?>';
//alert(theval);
$('<p>'+sessName+': '+theval+'</p>').appendTo('#content');
$.ajax({
type: "GET",
url: "savechat.php?msg="+theval,
//data: { value : theval },
success: function(data)
{
alert("success");
}
});
}
});
}