为什么我的$ .get()ajax在表单字段中显示响应?

时间:2018-06-14 14:42:10

标签: jquery ajax

我正在尝试了解ajax。我知道没有必要将字符串发送到服务器以使字符串大写。

它的作用:这是一个简单的AJAX请求,它涉及用户输入小写字母/字符串(在#user_text中),ajax然后接受此&将其转换为大写。

为什么这不起作用?:返回的字符串应该显示在第二个表单字段(#server_response)中,但是没有显示任何内容,尽管{{1 }}

我在控制台中收到此错误: Status Code: 200 OK这是localhost。

client.html:

Failed to load http://localhost/HowToUseAjaxWithJquery/server.php?user_text=Ma: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

server.php:

<html>
<head>
   <title> First AJAX Example </title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script type="text/javascript">

    function updateText() {

  //GET METHOD IN AJAX USING JQUERY
  var current_text = $('#user_text').val();
  $.get("http://localhost/HowToUseAjaxWithJquery/server.php" , "user_text="+current_text ,
        function( response , status , http ) {
             $('#server_response').val( response );
          } , "text"  );

      }

   </script>
</head>

 <body>
   <div>Input Text: <input type="text" id="user_text" name="user_text" onkeyup="updateText();" / /> </div> <br/>
   <div> Server Resp: <input type="text" id="server_response" name="server_response" readonly / /> </div>

 </body>
</html>

1 个答案:

答案 0 :(得分:0)

这是因为localhost(使用Xampp)没有使用相同的端口。在本地服务器上启用CORS是解决方案。这是一个非常好的Chrome扩展程序,可以为您执行此操作https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en