如何避免www和非www问题?

时间:2014-06-03 03:41:14

标签: javascript php cross-domain

<script type="text/javascript">

$(function () {
    $("#citynm1").autocomplete("http://www.mywebsite.com/getcity.php", {
        width: 160,
        autoFill: false,
        selectFirst: false
    });
});     

</script>

当站点URL以WWW开头时,此脚本正在运行,但如果WWW不可用,则此脚本无效。那我该怎么办?

1 个答案:

答案 0 :(得分:0)

    <script type="text/javascript">

    $(function () {

        var url="http://www.mywebsite.com/getcity.php"
         urlExists(url,function(exist){
               if(!exist){
                    url="http://mywebsite.com/getcity.php"   
               }
               urlExists(url,function(exist2){
                 if(exist2){
                   $("#citynm1").autocomplete(url,{
                       width: 160,
                       autoFill: false,
                       selectFirst: false
                     })  
                  }

               });

         }); 



    });     

    </script>

知道:

function urlExists(url, callback){
  $.ajax({
    type: 'HEAD',
    url: url,
    success: function(){
      callback(true);
    },
    error: function() {
      callback(false);
    }
  });
}