如何从Request :: createFromGlobals()

时间:2019-08-31 16:40:49

标签: javascript php symfony-3.4

我试图在旧项目中使用Symfony 3.4组件。有一个包含两个字段的城市和州的表格。我想将这两个字段发送到类方法。因此,我构建了一个中间PHP文件,以将数据传递给使用javascript。表单和javascript在这里。

     <form class="form-inline" id="addpharmacies">
    <div class="form-group">
        <label for="city" ><?php print xlt("City");?></label>
        <input type="text" class="form-control" id="city">
    </div>
    <div class="form-group">
        <label for="state"><?php print xlt("State");?></label>
        <input type="text" class="form-control" id="state">
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary" >Submit</button>
    </div>
</form>

let f = document.getElementById('addpharmacies');
f.addEventListener('submit', importPharm);

function importPharm() {
top.restoreSession();
let city = document.getElementById("city").value;
let state = document.getElementById("state").value;
if (city.length === 0 || state.length ===0) {
    alert("City and state must both be filled out") 
    return false;
}
let body = {"city": city, "state": state};
let req = new Request('pharmacyHelper.php', {method: "POST", body: body});
fetch(req)
    .then(response=> {
        if (response.status === 200) {
            return response.json()
        } else {
            throw new Error("Bad response from the server");
        }
    })
    .then(json => {
        alert(json) // Not a great UI experience
    })

}

如您所见,我正在使用侦听器通过javascript函数importPharm提交表单。 javascript通过对City和State字段的getElementById调用从表单获取数据。

创建一个请求,并将数据传递到请求中,并调用帮助程序文件以传递数据。我已验证某些内容已发送到帮助文件。但是当我执行getContent()时,可以看到[object Object]。

 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;

 $request = Request::createFromGlobals();
 $content = $request->getContent();
 file_put_contents("api.txt", $content);

当我尝试:

    $request->request->get('city','');

我什么也没得到。我尝试了在Symfony Site

上可以找到的所有组合

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

您还没有指定任何标头来澄清您的内容类型,因此Symfony检测您的内容类型并将其映射到Parameter Bag(尽管它显示了内容主体)是模棱两可的,请尝试添加:< / p>

Content-Type : application/x-www-form-urlencoded

header并将表单输入作为表单数据发送,然后重试,否则您将需要 json_decode 内容主体并将其作为数组或\ StdClass对象处理。 / p>

NB :使用表单数据,您的请求将如下所示

let body = "city="+city+"&state="+state;
let req = new Request('pharmacyHelper.php', {
    method: "POST",
    headers: {
        'Content-Type': 'application/x-www-form-url-encoded', 
        'Accept': 'application/json'
    },body: body});
fetch(req).then(response=> {
                    if (response.status === 200) {
                        return response.json()
                    } else {
                        throw new Error("Bad response from the server");
                    }
                })
                .then(json => {
                    alert(json) // Not a great UI experience
                })