如何使用PHP解决跨域问题

时间:2013-04-09 09:00:30

标签: javascript jquery ajax json

下面的代码工作正常,但我使用demo.php来解决跨域问题,如何使用php,bcs客户端不需要php来执行此操作

 $('#basic-search').submit(function(el){


        var searchdata=$('#search-text').val(); 

            $.ajax({
                  type:"POST" ,
              url:'demo.php',
              data:{
               address: 'http://search-harbinger-n5nyhive6kr72z37m6qrz2xxie.us-east-1.cloudsearch.amazonaws.com/2011-02-01/search?q='+searchdata+'*&results-type=json&return-fields=message&size=10', 
              },
              success:function(response){ 
                if(response!=""){
                response = jQuery.parseJSON(response);
                $.each(response.hits,function(indx,obj){
                    if($.isArray(obj)) {
                        $('.search-results').empty();    
                        $('.search-results').prepend('<div class="basic-results">Results ('+ obj.length+')</div>');
                        if(obj.length!="0"){
                        for(var i=0;i<obj.length;i++){
                            var $temp = '<div class="serach-results-items"><div class=""><b>ID : '+obj[i].id +'</b></div><div class="search-cont"> <b>Message :</b> '+obj[i].data.message+'</div></div>';
                            $('.search-results').append($temp);
                            $('.submit-btn').css('display','none');
                        }
                        }

                        else{
                        $('.search-results').append('<div><div>Your search-<b>'+searchdata+'</b>-did not match any documents.</div><div>Make sure that all words are spelled correctly.</div></div>');
                        $('.submit-btn').css('display','none');
                        }
                    }
                });

                }
                else{alert('something went wrong.');}
             }
            });

        });

1 个答案:

答案 0 :(得分:0)

您应该使用jsonp进行跨域调用,例如

    $.ajax({
          type:"POST" ,
          url:'demo.php',
          data:{
           address: 'http://search-harbinger-n5nyhive6kr72z37m6qrz2xxie.us-east-1.cloudsearch.amazonaws.com/2011-02-01/search?q='+searchdata+'*&results-type=json&return-fields=message&size=10', 
          }
         dataType: 'jsonp',
         jsonp: 'callback',