【问题标题】:posting json to slim with a form使用表单将 json 发布到苗条
【发布时间】:2015-10-28 23:14:02
【问题描述】:

我尝试使用 slim 以表单发布 json。

如果我使用 rest api,它可以工作。我将其设置为主体:

{
"url": "http://link.com"
}

发布到“api/generate”:

<?php

use Shorty\Models\Link;
use Shorty\Presenters\ErrorPresenter;
use Shorty\Presenters\LinkPresenter;

$app->post('/api/generate', function () use ($app) {

    $payload = json_decode($app->request->getBody());

    if(/*empty($payload) ||*/ !isset($payload->url) || empty(trim($payload->url))){
        $app->response->setStatus(400);

        return $app->response->write(
            new ErrorPresenter('1000', 'A URL is required.')
        );
    }

    if(!filter_var($payload->url, FILTER_VALIDATE_URL)){
        $app->response->status(400);

        return $app->response->write(
            new ErrorPresenter('1001', 'A valid URL is required.')
        );
    }

    $app->response->setStatus(201);

    $link = Link::where('url', $payload->url)->first();

    if($link){    
        return $app->response->write(
            new LinkPresenter($link)
        );          
    }

    $newLink = Link::create([
        'url' => $payload->url
    ]);

    $newLink->update([
        'code' => $newLink->generateShortCode($newLink->id)
    ]);

    return $app->response->write(
        new LinkPresenter($newLink)
    );  

});

它返回预期的结果:

{"url":"http:\/\/link.com","generated":{"url":"http:\/\/localhost:200\/phpacademy\/shorty\/public\/a","code":"a"}}

但我想通过表单发送 json。如果使用这个:

<form id='userForm'>
    <input type="text" name="url">
    <input type="submit" value="Get link!">
</form>

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){

        // show that something is loading
        $('#response').html("<b>Loading response...</b>");

        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.ajax({
            type: 'POST',
            url: 'api/generate', 
            data: $(this).serialize()
        })
        .done(function(data){

            // show the response
            $('#response').html(data);

        })
        .fail(function() {

            // just in case posting your form failed
            alert( "Posting failed." );

        });

        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

</body>
</html>

它不工作。 我得到{"error":{"code":"1000","message":"A URL is required."}}。 但是我看到“url=http%3A%2F%2Flink.cok”已经发布了。

【问题讨论】:

  • 您没有从表单中发布 JSON。
  • 真的吗?那我该如何发布 JSON 呢?
  • 使用 $.ajax contentType : "application/json",我可以发送 json,但就是这样:[{"name":"url","value":"link.com"} ]。我需要的是 [{"url": "link.com"}]。如何摆脱“名称-值”?

标签: php json slim


【解决方案1】:

我需要发送 json,但 json 作为“名称:值”,而不是默认的“名称:名称,值:值”。于是我发现:

var data = { };
$.each($('form').serializeArray(), function() {
    data[this.name] = this.value;
});

data = JSON.stringify(data);

我正在构建一个数据对象,每个属性都为“名称:值”。然后将对象解析成字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 2011-10-12
    • 2020-03-06
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多