简体   繁体   English

HTTP POST / GET请求PHP脚本和JSON响应

[英]HTTP POST/GET request to PHP script and JSON response

I have pages that send POST/GET requests to PHP scripts on the server. 我有页面将POST / GET请求发送到服务器上的PHP脚本。 All PHP scripts respond in JSON. 所有PHP脚本都以JSON响应。 Question is how to capture the JSON response at the client-side in JavaScript. 问题是如何在JavaScript中捕获客户端的JSON响应。

Example : when i submit the form register.html, i want to capture and manipulate (using Javascript) the JSON response returned from http://localhost/register.php . 示例:当我提交表单register.html时,我想捕获并操纵(使用Javascript)从http://localhost/register.php返回的JSON响应。

You have to make an AJAX request. 你必须提出一个AJAX请求。 You can do this quite simply by using a library such as jquery. 您可以通过使用诸如jquery之类的库来完成此操作。 Or a little more difficultly just using javascript. 或者只是使用javascript更难一点。

Using AJAX will change the current flow of your application though. 使用AJAX会改变应用程序的当前流程。 This follow example is using jquery 以下示例使用jquery

<form onSubmit="makeRequest(); return false;"></form>

function makeRequest() {
  $.post('register.php', formDataHereAsAnObject, function(response) {
     console.log(response) // this response is your json
  });

}

我可以推荐http://www.json.org/js.html获取使用JSON的详细说明。

The moment you submit a form in the classic sense, you're out of luck. 提交经典意义上的表格的那一刻,你运气不好。 What you want is to load the JSON response from the server. 你想要的是从服务器加载JSON响应。 To achieve this, there are a few possibilities 为实现这一目标,有一些可能性

  • Set the target of your form to an invisible iframe and do submit it, then take the JSON out of there via JS (old school) 将表单的目标设置为不可见的iframe并提交,然后通过JS(旧学校)将JSON从那里取出
  • Start an AJAX request (via a framework or directly), that ends up having your data in a JS variable 启动一个AJAX请求(通过框架或直接),最终将您的数据放在JS变量中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM