我正在尝试使用MAMP将一些聚合物元素属性与localhost上的MySQL数据库同步。
如何将SQL数据从PHP变量传递到Polymer数据绑定属性?
Polymer元素如下:
<iron-ajax id="ajax"
auto
url="../src/data/php/get_data.php"
last-response="{{lastResponse}}"
handle-as="text"></iron-ajax>
...
static get properties() { return {
lastResponse: {
type: Object,
value: {}
}
}}
lastResponse () {
console.log(this.lastResponse);
}
PHP脚本如下:
<?php
$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
答案 0 :(得分:0)
PHP函数
get_data.php
应该回显(不返回)JSON,如:
$res['data'] = 'Hello!';
echo json_encode($res);
和iron-ajax应设置为接收JSON:
handle-as="json"
就像在这里的文档一样
https://www.webcomponents.org/element/PolymerElements/iron-ajax/elements/iron-ajax
在Polymer中首先执行AJAX请求,然后接收数据:
get_data_responseHandler: function(e) {
console.log(e.detail.response);
}
这就是API点的创建方式。