PHP 会话在 Aurelia 中不工作
PHP session not working in Aurelia
我正在使用带有 PHP 作为后端的 Aurelia。这是我对其模型的看法:
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 post !isset($_SESSION['username'] 不会评估为真,但它确实意味着 PHP 会话不工作。
默认情况下 fetch
(构建 aurelia-fetch-client 的网络标准)不发送 cookie。您需要在请求初始化对象中使用 credentials: 'include'
。
两个很棒的获取资源:
代码:
this.http.fetch('dist/components/ses.php', {
credentials: 'include', // <-------------------------------------
method: 'post',
body: JSON.stringify(this.jsonobj)
})
我正在使用带有 PHP 作为后端的 Aurelia。这是我对其模型的看法:
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 post !isset($_SESSION['username'] 不会评估为真,但它确实意味着 PHP 会话不工作。
默认情况下 fetch
(构建 aurelia-fetch-client 的网络标准)不发送 cookie。您需要在请求初始化对象中使用 credentials: 'include'
。
两个很棒的获取资源:
代码:
this.http.fetch('dist/components/ses.php', {
credentials: 'include', // <-------------------------------------
method: 'post',
body: JSON.stringify(this.jsonobj)
})