【问题标题】:How to post variable into controller (PHP+AJAX+MVC)如何将变量发布到控制器中(PHP+AJAX+MVC)
【发布时间】:2016-05-25 03:22:11
【问题描述】:

我正在尝试使用 ajax 将变量发布到 php 控制器中:

$(".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);
 }

Ajax 发布变量成功,但控制器没有它。我认为,这将是不正确的 url,但它不适用于控制器文件的完整 url。

路由器来源:

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 控制器?

【问题讨论】:

    标签: php jquery ajax model-view-controller


    【解决方案1】:

    改成这个

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

    这会通过ajax提交正常的表单提交

    【讨论】:

    • 变量正在发布,但 php 没有返回任何东西
    • $data=$_POST['dataString']改成这个$data=$_POST
    【解决方案2】:

    试试下面的

    $(".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
    }
    });
    }
    });
    

    【讨论】:

    • 它只是在刷新我的 dom 元素.. 没有结果
    • 刷新是什么意思??
    • 我希望你有 2 条路由,一条用于 php,一条用于 ajax 脚本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2014-03-17
    相关资源
    最近更新 更多