[英]Ajax using information from PHP
I'm having trouble using the information I get from my PHP file after an AJAX call. 我在使用AJAX调用后从PHP文件中获取的信息时遇到问题。 I currently have the following AJAX code that triggers after clicking a button:
我目前有以下单击按钮后触发的AJAX代码:
<script>
$(document).ready(function(){
$('.button').click(function(){
$.ajax({
type: "POST",
url: "nano.php",
data: { action: "authenticate" }
}).done(function( msg ) {
alert( "Done: " + msg );
});
});
});
</script>
Than, in the nano.php file I do some authentication and information fetching. 在nano.php文件中,我做了一些身份验证和信息获取。 In the end of my PHP code I do the following:
在我的PHP代码的最后,我执行以下操作:
print_r($member_info);
print_r($activity_info);
This information (two arrays with a lot of information) appear in the alert box that is called in the Ajax done function, which means that this information is available in the client side. 此信息(两个包含大量信息的数组)出现在Ajax done函数中调用的警告框中,这意味着此信息在客户端可用。
I want to be able to treat the arrays and show the information on the page. 我希望能够处理数组并在页面上显示信息。 Is print_r the right way to send the information?
print_r是发送信息的正确方法吗? How can I treat and show the information in the arrays in my page after this?
在此之后,如何在页面中处理和显示数组中的信息?
To send an array from your PHP file back to Javascript through AJAX use: 要通过AJAX将PHP文件中的数组发送回Javascript,请使用:
echo json_encode($array);
Applies to strings too. 也适用于字符串。
And change the expected response type to json
in your jQuery.ajax call: 并在jQuery.ajax调用中将预期的响应类型更改为
json
:
$.ajax({
type: "POST",
url: "nano.php",
dataType: 'json',
data: { action: "authenticate" }
}).done(function( msg ) {
alert( "Done: ");
console.log(msg); // <- javascript array or object
});
(or send a application/json
content-type header from PHP) (或从PHP发送
application/json
内容类型标头)
The correct way to do this is use a empty mark up in your html like <div id="response"></div>
正确的方法是在你的html中使用空标记,例如
<div id="response"></div>
In your php: 在你的PHP:
print_r(json_encode($member_info));
print_r (json_encode($activity_info));
And in your ajax call use this div to hold ajax reponse like this: 在你的ajax调用中使用这个div来保存ajax响应,如下所示:
$.ajax({
type: "POST",
url: "nano.php",
data: { action: "authenticate" }
}).done(function( msg ) {
$("#response").html(msg);
});
Return a message in JSON, it's easier to manage it later in jQuery. 在JSON中返回一条消息,稍后在jQuery中管理它会更容易。
PHP: PHP:
$data = array( 'some_var' => 'some_value' );
echo json_encode( $data );
exit;
And then in jQuery: 然后在jQuery中:
<script>
$(document).ready(function(){
$('.button').click(function(){
$.ajax({
type: "POST",
url: "nano.php",
data: { action: "authenticate" }
}).done(function( msg ) {
var data_object = JSON.parse(msg); // Create a Javascript object/array from the JSON
// Here you can use the data inside the array/object
alert( data_object.some_var );
});
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.