Bored to do a www.jiazhuangma.com, technology does not pass through the background, want to read the data directly in WordPress. Do Ajax read the background data on the Internet casually searched a section of code to use WordPress $wpdb class to read MySQL database, is so casually, found someone else's head to the end of the code, began my mistake trip.
The main problems are:
1,non-object
Chinese characters in 2,json,/by transcoding
3,chrome can normally access the PHP file, ie display HTTP 404,ajax when the head display 404, but the response body is correct, is the JSON I want.
First put the code found on the Internet:
<?php
global $wpdb;
$a = $wpdb->get_results ("Select Id,post_title from Wp_posts″");
echo Json_encode ($a);
? >
At this time will be an error, non-object;
Some people on the internet say that they can add require_once (' wp-blog-header.php '); So congratulations on your winning, you'll find that chrome can normally access PHP files, ie display HTTP 404,ajax when the head display 404, but the response body is correct.
Modified to require_once (' wp-config.php ');
The resulting JSON is the transcoding after the need for the Echo json_encode ($a);
Modified to echo str_replace ("\\/", "/", Json_encode ($a, json_unescaped_unicode)); The results are correct.
Final Result:
<?php
require_once (' wp-config.php ');
Global $wpdb;
$a = $wpdb->get_results ("Select Wp_posts.id,wp_posts.post_title,wp_posts.guid from wp_posts inner join WP_TERM_ Relationships on Wp_term_relationships.object_id=wp_posts.id where wp_term_relationships.term_taxonomy_id=3 wp_term_relationships.object_id DESC LIMIT 5″);
Echo str_replace ("\\/", "/", Json_encode ($a, json_unescaped_unicode));
? >
The above is a small series to introduce the use of WordPress $wpdb class to read MySQL database to do AJAX problems in how to solve the problem, I hope to help.