【发布时间】:2015-08-19 16:58:25
【问题描述】:
来自 mySql 的 php 数组不会在 DOM 中显示为 json 对象
我不知道该怎么称呼这个问题。我有一个 jquery ajax get 语句:
function fill_contact(evt) /** display click event **/
{
var country_id = evt.target.id
document.getElementById('country_name').firstChild.data = country_id
/** Perform an asynchronous HTTP (Ajax) request. **/
$.ajax({
url:'../core/database/mapString.php', /** the script to call to get data **/
data:{ "country_name": country_id }, /** pass the country name as a name/value pair. **/
type:'GET',
dataType: 'json', /** data format **/
success: function(json_data){ /**Function for showing data. **/
/** Update html content **/
console.log(json_data);
/**Set output element html **/
$('#firstname').html(json_data.firstname);
$('#lastname').html(json_data.lastname);
$('#email').html(json_data.email);
$('#photo').html(json_data.photo);
},
/**error handling. **/
error: function(xhr, status, error) {
//var err = eval("(" + xhr.responseText + ")");
$('<div id="fb-root" />').html(xhr.responseText).prependTo('body');
},
});
}
这工作并将 country_name 发送到服务器,然后 sql 获取并处理它。当我回显结果时,它显示了正确的结果。如果单击的国家/地区没有信息,即。如果为空,则数组发布正确的默认值(json 对象)并且它们出现在 DOM 中的正确位置。但是,如果该国家/地区有信息:则它不会显示在 DOM 中。 ???仅显示在回声中。所以数据就在那里。
if (isset($_GET["country_name"])) {
$country_name = $_GET["country_name"];
/** run prepare to select records **/
$stmt = $dbh->prepare("SELECT firstname, lastname, email, photo FROM reps WHERE country = :country_name");
$stmt->bindParam(':country_name', $country_name, PDO::PARAM_STR);
$stmt->execute();
/** Values to fill up the form **/
$result = $stmt->fetch();
}
/** create the array **/
$json_data=array();
/** Check if there is data, if not give default data **/
if(empty($result)) {
$json_data = array( 'firstname' => 'www.aeea.org',
'lastname' => '',
'email' => 'africa@aeea.org',
'photo' => '../images/Afrizone.png');
}
else { //******* How do I build this array from database results? *******//
$json_data = array( 'firstname' => $result['firstname'],
'lastname' => $result['lastname'],
'email' => $result['email'],
'photo' => $result['photo']);
/** Test if the info is there - it is **/
echo $json_data['firstname'] . " " . $json_data['lastname'] . '<br />';
echo $json_data['email'] . '<br />';
}
/** built in PHP function to encode the data in to JSON format **/
header('Content-Type: application/json');
echo json_encode($json_data);
return $json_data;
/*** close the database connection ***/
$dbh = null;
你能帮我解决我想念的地方吗?
提前感谢您的宝贵时间。
衍生自:displaying data from sql from clicking on svg map 和https://stackoverflow.com/questions/30383629/using-a-svg-image-click-event-to-get-data-from-sql-using-ajax-and-json
【问题讨论】:
-
console.log(json_data);这个语句有你想要的所有数据吗?
标签: php jquery mysql arrays ajax