我试图将输入值发送到同一页面中的代码段,但它不起作用。现在,我无法获取代码段中的值。这是我当前的代码:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
有什么建议吗?
如果你想在不刷新页面的情况下获得值,你必须使用javascript,你可以试试这个:
$('#hour').onchange = function () {
//type your code here
}
顺便说一句,你的php脚本是服务器端的,根据这一点,如果没有post/submit/refresh ,你就不能使用这个值
无论何时使用
<input type="submit">
它将数据发送到表单的操作,因此每当您在调用onclick函数之前单击提交按钮时,它都会将数据发送给该操作并刷新页面。因此,与其使用输入元素,不如尝试这样的
<button id="submit_form"> Submit </button>
两件事,1.正如yesh所说,您需要将输入submit更改为button type=button
,并在该按钮上添加onClick
功能。或者,您可以在函数行function sampleFn(){}
中给定一个javascript函数,并调用该函数onSubmit
的形式。2.由于脚本在dom加载之前执行,可能找不到var submit_button = $('#submit_form');
,因此需要在document.ready
内部赋予javascript函数。在这种情况下,浏览器控制台中将出现错误。
尽量在帖子中添加错误,因为这将有助于轻松调试。
不可能在同一页上进行。您可以编写对另一个包含数据的页面的ajax调用,在那里您可以使用数据执行函数。
类似这样的东西
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}