如何通过ajax获取响应,其中dataType为jsonp和有效负载变量

时间:2015-10-13 08:09:13

标签: javascript jquery ajax jsonp payload

我有一个外部网络服务网址http://www.theienable.com/interntest/interntest.php,当我使用php curl发送帖子请求时,我得到正确的响应,数据通过发送邮件字段作为json编码&给我输出。

  <?php
  $curl = curl_init();
  curl_setopt_array($curl, array(
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL => 'http://www.theienable.com/interntest/interntest.php',
  CURLOPT_USERAGENT => 'Sample Test Request',
  CURLOPT_POST => 1,
  CURLOPT_POSTFIELDS => json_encode(array('password' => 'test12345'))
  ));
  // Send the request & save response to $resp
 $resp = curl_exec($curl);
 echo $resp;
 ?>

我的网络服务O / p如下所示,这是完美的。

{"error":"","backgroundURL":"http:\/\/www.theienable.com\/interntest\/bgpattern237tfg98gg.png","goButtonURL":"http:\/\/www.theienable.com\/interntest\/gobutton32rf72gf.png","closeButtonURL":"http:\/\/www.theienable.com\/interntest\/closebutton23rg28f.png"}

当我使用ajax iam对同一个webservice url发布post请求时,没有得到正确的响应,这是我的ajax代码。

   <script>

   function requestWebService(){
        var data={"password":"test12345"};
        $.ajax({
        url:"http://theienable.com/interntest/interntest.php",
        data:JSON.stringify(data),
        type:'POST',
        dataType:'jsonp',
        contentType: "application/json",
        async:false,
        success:function(response,xhr){
           $('.resultArea').html(response);
        },
        error:function(xhr,ajaxOptions,thrownError){
        $('.resultArea').html("Response: "+JSON.stringify(xhr));
        }
        });
   } 

 </script>

1 个答案:

答案 0 :(得分:0)

我尝试了你的代码。 结果是跨站点脚本的问题。

XMLHttpRequest cannot load http://theienable.com/interntest/interntest.php.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://myserver.local is therefore not allowed access.

我不知道您的网站是否有访问权限。 看看https://en.wikipedia.org/wiki/Cross-site_scripting