我使用Aurelia和PHP作为后端。以下是我对其型号的看法:
home.html
<template>
<require from="datepicker.js"></require>
<form submit.delegate="submit()">
<input value.bind="name"></input>
<input value.bind="age"></input>
<button type="submit" name="submit">Submit
</button>
</form>
</template>
home.js
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
@inject(HttpClient)
export class Home {
name;
age;
constructor(http) {
this.http = http;
}
submit() {
this.jsonobj = {
'name': this.name,
'age': this.age
};
if (this.jsonobj.name && this.jsonobj.age) {
this.http.fetch('dist/components/ses.php', {
method: 'post',
body: JSON.stringify(this.jsonobj)
})
.then(response => response.json())
.then(data =>
{
console.log(data);
});
}
}
}
下面是PHP脚本:
ses.php
<?php
session_start();
$word = 'lol';
if(!isset($_SESSION['username'])){
$_SESSION['username'] = 'kil';
}
$input = file_get_contents('php://input');
$input_json_array = json_decode($input);
echo json_encode(array('item' => $_SESSION['username']));
?>
我预计在第一次调用脚本后,$_SESSION['username']将被设置为'kil'。所以在下一篇ajax文章中!isset($_SESSION['username']的计算结果不会为true,但它确实为true,这意味着PHP会话不工作。
默认情况下,fetch
(aurelia fetch客户端所基于的web标准)不发送cookie。您需要在请求init对象中使用credentials: 'include'
。
两个伟大的资源获取:
- https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
- https://davidwalsh.name/fetch
代码:
this.http.fetch('dist/components/ses.php', {
credentials: 'include', // <-------------------------------------
method: 'post',
body: JSON.stringify(this.jsonobj)
})