PHP和js-ajax的行为很奇怪(里面有解释)

php and js-ajax acting funny (explanation inside)

本文关键字:解释 js-ajax PHP      更新时间:2023-09-26

我有这个ajax的麻烦。回报很有趣。这个开关似乎总是以#about为真来计算。并将switch语句的其余部分包含在#page变量中。例如,我的PHP代码打印了这个(以及它应该打印的#about),底部的代码应该澄清我的意思。

$page ='

在我的页面上,我在下面看到了它应该回显的

   ';
           break;
    case '#register' :
           $page = 'k';
           break;
    case '#contact' :
          $page = 'a';
    break;
     case '#a' :
        $page = ' b';
        break;
     case '#b' :
        $page = '<p> c</p>';
        break;

      default;
    echo "def";
   }
   echo $page;

更不用说它甚至不能用于#contact或#a, #b等。我不知道为什么。不管传递的url是什么,看起来好像#about是用它返回的内容调用的(即使它返回的是about或更多)。

我真的很感激你的帮助!谢谢你

下面是我的代码:

the js =]

$(document).ready(function () {

    //highlight the selected link
    $('a[href=' + document.location.hash + ']').addClass('selected');
    //Seearch for link with REL set to ajax
    $('a[rel=ajax]').click(function () {
        //grab the full url
        var hash = this.href;
        //remove the # value
        hash = hash.replace(/^.*#/, '');
        //clear the selected class and add the class class to the selected link
        $('a[rel=ajax]').removeClass('selected');
        $(this).addClass('selected');
        //hide the content
            $('#content').hide();
        console.log(this.href);
        //run the ajax
        getPage();
        //cancel the anchor tag behaviour
        return false;
    }); 
});

function pageload(hash) {
    //if hash value exists, run the ajax
    if (hash) getPage();    
    console.log("k");
}
function getPage() {
    //generate the parameter for the php script
    var data = 'page=' + encodeURIComponent(document.location.hash);
    $.ajax({
        url: "loader.php",  
        type: "GET",        
        data: data,     
        cache: false,
        success: function (html) {  
            //add the content retrieved from ajax and put it in the #content div
            $('#content').html(html);
            //display the body with fadeIn transition
            $('#content').fadeIn('slow');       
        }       
    });
}

the PHP =]

switch($_GET['page']) {
 case '#about' :
        $page = ' HTML stack overflow formats it, anyways';
        break;
 case '#register' :
        $page = 'k';
        break;
 case '#contact' :
        $page = 'a';
        break;
  case '#a' :
     $page = ' b';
     break;
  case '#b' :
     $page = '<p> c</p>';
     break;

   default;
 echo "def";
}
echo $page;

再次感谢您!

同样在php文件中,试着把这个放在脚本的顶部:

头(content - type: text/html);