Zend Framework 2 - AJAX Request from other server

2019-02-23 16:37发布

I have 2 domains (domain A, domain B).

On domain A is placed ZF2 application, and everything is ok.

On domain B is placed Landing Page (small site with form to collect data).

From Landing Page I want send form data to application on domain A (AJAX Request).

Unfortunatelly ZF2 app on domain A didn't receive data, and didn't show results. Everything is ok when I make AJAX Request from same domain where ZF2 app is.

I tried use JSONP but without success.

I don't have any other clue how to force this to work.

3条回答
我想做一个坏孩纸
2楼-- · 2019-02-23 17:14

As Bodgan's answer stated, this is a browser security issue rather than a ZF2 issue. One popular way to get around it is to change the ACCESS-CONTROL-ALLOW-ORIGIN of your domain A to allow requests from domain B. This and other solutions are discussed on the Mozilla Developer Network (MDN) page for HTTP access control (CORS).

Basically you need to indicate to the receiving server (domain A) that it is okay to respond to requests for resources. You can do this within a .htaccess file placed in the web root of domain A. Below is some simple sample code that indicates to domain A that it should respond to resource sharing requests from all domains: *. The MDN article linked to above goes into a more in-depth discussion of "Cross-Origin Resource Sharing (CORS)". Keep in mind that there are security implications, and in most scenarios you do not want to open up your server to requests from * origins, but rather to a specific host controlled by yourself.

Options +FollowSymlinks
RewriteEngine on

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
查看更多
Lonely孤独者°
3楼-- · 2019-02-23 17:14

Cross-domain ajax requests are forbidden due to security reasons (this is called Same origin policy). http://en.wikipedia.org/wiki/Same_origin_policy

查看更多
Root(大扎)
4楼-- · 2019-02-23 17:34

You could change your htaccess file to support but the easiest way would be to use the response class:

$this->_response->setHeader('Access-Control-Allow-Origin', '*');

http://framework.zend.com/manual/2.0/en/modules/zend.http.response.html

If you are using json as your end point data source, use this in conjunction with the json helper which will set your encoding headers and a few other things too

$this->_helper->json->sendJson($jsonIsite);

http://framework.zend.com/manual/2.0/en/modules/zend.json.introduction.html

there is https://github.com/zf-fr/zfr-cors for advanced CORS with ZF2 but a simple json endpoint with the above should work just fine.

查看更多
登录 后发表回答