douzhantao2857 2014-07-24 09:35
浏览 32

Ajax Slim Framework

I am working on a ajax to call the slimframework API and post data to the DB. But ajax PUT do not work? I keep getting a 404 in ajax .

This works

<form action="http://myapi.com/api/key/514315/push" method="post">
<input type="input" name="test" value="test">

<input type="submit" value="Submit"/>

Trying in Ajax, this oes not work : returns 404 when sending data, as if you accessed API without sending a put request.

<script type="text/javascript">
var Data = [
    {
        "Name" : 'Home',
        "Description" : "This is a test description",
        "Keywords" : "Keyword One, Two, Threeh",
        "Menu" : 1,
        "Parent" : 0
    },
    {
        "Name" : 'About',
        "Description" : "This is a About description",
        "Keywords" : "Keyword One, Two, Threeh",
        "Menu" : 2,
        "Parent" : 0
    }

];

var rootURL = "http://myapi.com/api/key/514315/push";

$.each(Data, function(key, value) {

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: rootURL,
        dataType: "json",
        data: Data[key],
        success: function(data, textStatus, jqXHR){
            alert('Article Added');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('Add Article error: ' + textStatus);
        }
    });

});

PHP

$app->post('/key/:key/push', function ($key) {


        $app = new \Slim\Slim();

        $body = $app->request->getBody();

        $singleRequest =  $app->request->params('test');

        echo "<pre>";
        print_r($body);
        echo "</pre>";

        echo "<hr>";


        echo "<pre>";
        print_r($singleRequest);
        echo "</pre>";


});

$app->run();

Any Ideas?

  • 写回答

1条回答 默认 最新

  • duanrong0738 2014-07-24 10:08
    关注
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    if(array_key_exists('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', $_SERVER)) {
        header('Access-Control-Allow-Headers: '
               . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
    } else {
        header('Access-Control-Allow-Headers: *');
    }
    
    if("OPTIONS" == $_SERVER['REQUEST_METHOD']) {
        exit(0);
    }
    

    Added this into PHP

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置