首页 > 解决方案 > 将 Json 数据从我的 html 页面发送到 php

问题描述

我从stackoverflow中获取了一个代码并创建了一个“index.htm”页面,它还将一个json数据从html页面发送到php这里它是“test.php”

当我尝试提交数据并在 Web 开发工具中查看时,我总是收到此错误:

jquery.min.js:4 从源“null”访问“file:///C:/Users/1701053/Desktop/ClientServer%20demo/test.php”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求是仅支持协议方案:http、data、chrome、chrome-extension、https。

这是我的代码

<!DOCTYPE html>
<html>

<head>

 </head>
<body>

<form id="form" action="" method="post">
 Name: <input type="text" name="name"><br>
 Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>

<script 
  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> 
</script>
 <script>
   $(document).ready(function(){
      // click on button submit
       $("#submit").on('click', function(){
          // send ajax
           $.ajax({
              url: 'test.php', // url where to submit the request
              type : "POST", // type of action POST || GET
              dataType : 'json', // data type
              data : $("#form").serialize(), // post data || get data
              success : function(result) {
                  // you can see the result from the console
                  // tab of the developer tools
                  console.log(result);
              },
                 error: function(xhr, resp, text) {
                  console.log(xhr, resp, text);
               }
             })
      });
   });

     </script>
     </body>
     </html>

测试.php

<?php

   // this is just a test
    //send back to the ajax request the request

   echo json_encode($_POST);
?>

注意:这不是我自己的工作,我将其用作参考,以了解如何仅使用 javascript 将 Json 对象实际发送到服务器

标签: jqueryajax

解决方案


简单地说,XMLHttpRequest()当 URL 以file:///. 功能也$.ajax()没有用。

XMLHttpRequest()适用于http://https://URL,因此请尝试从任何Web 服务器(如XAMPP )运行此页面


推荐阅读