使用Symfony2进行跨域Ajax请求(使用FOSUserBundle的示例)

时间:2015-11-18 13:58:59

标签: javascript php ajax symfony cross-domain

我有一个域名A" xbo.dev"和一个子域B" blog.xbo.dev"。

例如,在B域上,我想向域A函数发出Ajax请求。

我尝试使用FOSUserBundle身份验证。我做了什么:

    var xhr = new XMLHttpRequest();

      if ('withCredentials' in xhr) {
          xhr.open('POST', 'http://xbo.dev/ajax/check_login_ajax', true);
          // I am using hard coding for the URL because with Routing.generate I would have this URL : http://blog.xbo.dev/ajax/check_login_ajax
          // which is not good because the request is on a different domain
          xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 400) {
                  console.log(xhr);
                  console.log('ok');
              } else {
                  console.log('ko');
              }
          }
      };
      xhr.send(encodeURI('_username=' + $('#co_'+varName+'username').val() + '&_password=' + $('#co_'+varName+'password').val() + '&_remember_me=' + false + '&_csrf_token=' + $('#co__csrf_token').val()));

我有一个&#34; ok&#34;我的请求显示但没有什么特别的事情发生(我应该有类似&#34;不良凭证和#34;或者#34;成功&#34;(或其他),由FOSUserBundle check_login_ajax函数返回,但其中没有一个是显示...)

我该怎么办?

编辑1:这是我每次都有的结果,登录/密码是否正确

Here is the Ajax result

使用正常的$ .ajax,我有这个:

Here is the Ajax result

1 个答案:

答案 0 :(得分:1)

您需要对relax the same-origin policy实施某些内容,例如CORS

关于硬编码与使用路由器生成URL的代码说明,Symfony的路由器supports hostnames