我使用以下Ajax请求传递数据:
var query = {
"username" : $('#username').val(),
"email" : $('#email').val(),
}
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
success : function(html) {
// output
}
});
正在处理查询的我的php文件(process-registration.php)如下所示:
require_once 'db.php';
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
// Include new user into database
$db -> query("INSERT INTO users (username, email) VALUES ('$username', '$email');");
//Identify user id of this new user (maybe there is a faster way???)
$results = $db -> query("SELECT * FROM users WHERE username='$username'");
while ($result = $results->fetch_assoc()) {
$user_id = $result['id'];
}
// My output?
现在我的问题是:我如何告诉Ajax命令/ PHP脚本返回两个元素:
<p>You have registered successfully</p>
我需要user_id,因为在前端我希望将它作为GET参数包含到按钮的href中#34;转到管理区域&#34;这将在Ajax请求完成后出现。
答案 0 :(得分:0)
试试这个:
$response = array('user_id'=>$user_id,'message'=>'Success - user created');
echo json_encode($response);
这将返回一个可以在JS中访问的json对象。
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
dataType: 'json',
success : function(html) {
// output - do something with the response
console.log(html.user_id);
console.log(html.message);
}
});
答案 1 :(得分:0)
我认为最好通过在不同值之间放置一个特殊字符(我使用%或#)来更改字符串中的数组。在您的情况下,只需回显'
您已成功注册
%'。$ user_id ;.现在爆炸响应字符串并使用它们。