我有一个ajax调用...
$(function(){
$('#registerUser').submit(function() {
$.ajax({
url: 'http://www.mysite.co.uk/path/register/add_user.php',
type: 'post',
data: form.serialize(),
dataType: 'json',
crossDomain : true,
timeout: 5000,
success: function(msg){
alert(msg.name);
},
error: function(){
alert('There was an error loading the data.');
}
});
});
});
当我在 PHP 文件中回显一个 json 对象时,这一切都很好。然而,当使用我的类回显它时,它会在页面上回显,但在与 ajax 函数一起使用时不起作用 - 没有返回任何内容。
值得一提的是,我是 OOP 的菜鸟。我试图返回的对象只是一个与函数无关的简单对象,仅用于测试目的。
<?php
include('../config/.db.php');
include('../config/headers.php');
$firstName = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
class user{
public $returnArray;
public function addUser($firstName, $surname, $email, $password, $mysqli){
$stmt = $mysqli -> prepare("INSERT INTO users(name, surname, email, password) VALUES (?,?,?,?)");
$stmt -> bind_param("ssss", $firstName, $surname, $email, $password);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> fetch();
$stmt -> close();
$array = array('name'=>'andre');
$this->returnArray = json_encode($array);
}
}
$user = new user;
$user->addUser($firstName, $surname, $email, $password, $mysqli);
echo $user->returnArray;
?>
请求/响应
POST /intheloop/register/add_user.php HTTP/1.1
Host: www.mysite.co.uk
Connection: keep-alive
Content-Length: 47
Accept: application/json, text/javascript, */*; q=0.01
Origin: null
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Form Dataview sourceview URL encoded
name:a
surname:a
email:a
password:a
password2:a
Response Headersview parsed
HTTP/1.1 200 OK
Date: Sat, 26 Jan 2013 20:51:36 GMT
Server: Apache
X-Powered-By: PHP/5.3.15
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,PUT,POST,OPTIONS,DELETE
Keep-Alive: timeout=5, max=75
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json