php
  • jquery
  • ajax
  • model-view-controller
  • 2016-05-25 40 views 0 likes 
    0

    我試圖張貼變量到PHP控制器使用Ajax:如何發佈變量到控制器(PHP + AJAX + MVC)

    $(".inp_pr").keypress(function(f) { 
    if (f.which == 13) { 
    dataString = 'qwe'; 
    $.ajax({ 
    type: "POST", 
    url: "/prwrk/", 
    data: 'dataString=' + dataString, 
    success: function(data) { 
    alert('<?php echo($data)?>'); 
    } 
    }); 
    event.preventDefault(); 
    } 
    }); 
    

    控制器來源:

    function action_index() 
    { 
    $data=$_POST['dataString']; 
    $this->view->generate('prwrk_view.php', 'template_view.php',$data); 
    } 
    

    阿賈克斯的職位不同程度的成功,但控制器沒有它。我認爲,這將是不正確的網址,但它不是完整的網址到控制器文件。

    路由器來源:

    class Route 
    { 
    static function start() 
    { 
    
    $controller_name = 'Main'; 
    $action_name = 'index'; 
    
    $routes = explode('/', $_SERVER['REQUEST_URI']); 
    
    if (!empty($routes[1])) 
    { 
        $controller_name = $routes[1]; 
    } 
    
    
    
    
    if (!empty($routes[2])) 
    { 
        $action_name = $routes[2]; 
    } 
    
    
    
    $model_name = 'Model_'.$controller_name; 
    $controller_name = 'Controller_'.$controller_name; 
    $action_name = 'action_'.$action_name; 
    
    
    
    $model_file = strtolower($model_name).'.php'; 
    $model_path = "application/models/".$model_file; 
    if(file_exists($model_path)) 
    { 
        include "application/models/".$model_file; 
    } 
    
    
    $controller_file = strtolower($controller_name).'.php'; 
    $controller_path = "application/controllers/".$controller_file; 
    if(file_exists($controller_path)) 
    { 
        include "application/controllers/".$controller_file; 
    } 
    else 
    { 
    
        Route::ErrorPage404(); 
    } 
    
    
    $controller = new $controller_name; 
    $action = $action_name; 
    
    if(method_exists($controller, $action)) 
    { 
    
        $controller->$action(); 
    } 
    else 
    { 
    
        Route::ErrorPage404(); 
    } 
    
    } 
    
    function ErrorPage404() 
    { 
    $host = 'http://'.$_SERVER['HTTP_HOST'].'/'; 
    header('HTTP/1.1 404 Not Found'); 
    header("Status: 404 Not Found"); 
    header('Location:'.$host.'404'); 
    } 
    } 
    

    如何交變量來我的PHP控制器是否正確?

    回答

    0

    改變這種

    data:$("#formID").serialize(), 
    

    與此提交正常提交表單通過Ajax

    +0

    變量被髮布,但PHP沒有返回東西 –

    +0

    改變'$數據= $ _ POST ['dataString']'到這個'$ data = $ _ POST' –

    +0

    現在返回「數組」 –

    0

    請嘗試以下

    $(".inp_pr").keypress(function(f) { 
    if (f.which == 13) { 
    dataString = 'qwe'; 
    $.ajax({ 
    type: "POST", 
    url: "/prwrk/", 
    data: {dataString:dataString}, 
    success: function(data) { 
    $('body').append(data);//change the body to your dom element 
    } 
    }); 
    } 
    }); 
    
    +0

    這只是刷新我的DOM元素..沒有結果 –

    +0

    你是什麼意思提神? – madalinivascu

    +0

    我希望你有2個路由一個用於php,另一個用於ajax腳本 – madalinivascu

    相關問題