jQuery Ajax如何实际工作 [英] How does jquery ajax actually work
问题描述
说我有一个这样的表单(取自一本关于jquery的书):
Say I have a form like this (taken from a book on jquery):
<body>
<form>
<label>Enter your Name</label>
<input type="text" name="uname" class="uname"/> <br/>
<input type="submit" id="submit"/>
</form>
<div id="message"></div>
</body>
和这样的ajax函数:
and an ajax function like this:
$(document).ready(function() {
$('#submit').click(function () {
var name = $('.uname').val();
var data = 'uname=' + name;
$.ajax({
type:"POST",
url:"welcome.php",
data: data,
success: function (html) {
$('#message').html(html);
}
});
return false;
});
});
,脚本文件如下所示:
<?php
$name = $_POST['uname'];
echo "Welcome ". $name;
?>
它可以工作,但这是我无法理解的.如果welcome.php脚本从POST数组获取$ name的值,为什么它需要ajax请求将数据发送给它? POST数组肯定已经包含了该信息?
it will work but here's what I can't understand. If the welcome.php script gets the value of $name from the POST array, why does it need to have the data sent to it by the ajax request? The POST array already contains that information surely?
此外,我的理解是ajax请求采用键/值对的形式,但数据以uname = name的形式发送,但键/值对通常没有等号.
Also, my understanding is that the ajax request is in the form of key/value pairs but the data is sent in the form uname=name but key/value pairs don't normally have an equals sign.
这是怎么回事-它可以工作,但是对我来说没有意义,我讨厌只打入我死记硬背的代码.
What's going on here - it works but it doesn't make sense to me and I hate just punching in code I have learnt by rote.
推荐答案
问题与您的代码有关
var data ='uname ='+名称;
use
var data ='{uname:'+ name +'}';
因为它是post方法
Issue is with your code
var data = 'uname=' + name;
use
var data = '{uname:' + name + '}';
because its a post method
这篇关于jQuery Ajax如何实际工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!