我正在尝试发布数据并使用jQuery Ajax Post接收响应,我不确定为什么我的代码无效。
<script>
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
cache: false,
success: function(data){
console.log(data.stack);
console.log(data.key);
},
error:function(){
alert("failure");
}
});
return false;
});
});
</script>
<form autocomplete="off" class="ui fluid form segment" method="post">
<div class="ui fluid form segment">
<div class="two fields">
<div class="field">
<label>Email/Username</label>
<input placeholder="Email/Username" name="username" id="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input placeholder="Password" name="password" id="password" type="password">
</div>
</div>
<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
</div>
</form>
我的test3
页面包含:
<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
}
?>
答案 0 :(得分:1)
这对我有用:
$('#form').submit(function (event) {
event.preventDefault();
var data = $('#form').serialize();
$.ajax({
type: 'post',
dataType: 'json',
data: data
}).done(function (resp) {
console.log(resp);
});
});
在PHP方面,你可能需要这样的东西:
header('Content-Type: application/json');
echo json_encode($arr);
答案 1 :(得分:0)
试试这个。它会起作用。
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3.php',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
async: true,
success: function(data){
var obj = jQuery.parseJSON(data);
if(obj)
{
for(i=0;i<obj.length;i++) {
console.log(obj[i].stack);
console.log(obj[i].key);
}
} else {
console.log("Empty Result");
}
},
error:function(){
alert("failure");
}
});
});
});
<script>
你的test3.php脚本将是:
<?php
$arr=array();
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr[] = array(
'stack'=>'overflow',
'key'=>'value'
);
}
echo json_encode($arr);
?>