我是PHP / AJAX的新手,我试图在没有页面刷新的情况下获取表单值。我尝试过各种代码,但似乎都没有。没有任何反应或者我得到一个未定义的索引通知。我尝试过使用isset()和empty(),但这些似乎也不起作用。任何帮助表示赞赏。这是我的javascript函数:
{
var hr = new XMLHttpRequest();
var url = "parser.php";
var fn = document.getElementById("firstname").value;
var vars = "firstname="+fn;
//document.write(vars);
//open() method of XMLHttpRequest object
hr.open("get",url,true);
//to send url encoded variables in the request
hr.setRequestHeader("Content-type", "application/w-www-form-urlencoded");
hr.onreadystatechange = function () {
if(hr.readyState == 4 && hr.status == 200){
var returnData = hr.responseText;
document.getElementById("status").innerHTML = returnData;
}
};
//send data to PHP----wait for response to update status div
hr.send(vars); //execute request
document.getElementById("status").innerHTML = "processing...";
}
这是我尝试的另一种方法(代码在javascript函数中):
{
var name = document.getElementById('firstname').value;
var dataString = "name"+name;
$.ajax({
type: "post",
url: "validate.php",
data: dataString,
cache: false,
success: function (html) {
$('#result').html(html);
}
});
return false;
}
这是我的php文件,它将返回数据:
<?php
if(isset($_POST['firstname'])) {
$name = $_POST['firstname'];
echo 'Name:' . $name;
}
这是输入标签:
First name:<input id="firstname" name="firstname" type="text"><br>
答案 0 :(得分:0)
我认为您的数据字符串不正确,您缺少“=”
var dataString = "name"+name;
var dataString = "name="+name;
但您也可以尝试插入这样的对象:
$.ajax({
type: "post",
url: "validate.php",
data: {"name":name},
cache: false,
success: function (html) {
$('#result').html(html);
}
答案 1 :(得分:0)
将代码包装在文档就绪语句中,单击表单提交按钮触发代码,不要忘记将jquery库添加到页面
$(function(){
$('[type="submit"]').on('click',function(e){
e.preventDefault();
var name = $('#firstname').val();
var dataString = {name:name};
$.ajax({
type: "post",
url: "validate.php",
data: dataString,
cache: false,
success: function (html) {
$('#result').html(html);
}
});
});
});