用形式发布json

时间:2015-10-28 13:43:16

标签: php json slim

我尝试用一​​个使用slim的表单发布json。

如果我使用休息api,它可以工作。我把它设为身体:

ExternalDefinitionCreationOptions

发布到'api / generate':

private static Definition GetSimpleParameterDefinition(UIApplication uiApp, Document doc, DefinitionGroup defGroup, string name)
{
    var definition = defGroup.Definitions.FirstOrDefault(d => d.Name == name);
    if (definition != null) return definition;

    var parameterType = ParameterType.Text;

    var defOptions = new ExternalDefinitionCreationOptions(name, parameterType);
    BuiltInCategory target = BuiltInCategory.OST_Furniture;
    var cat = doc.Settings.Categories.get_Item(target);

    var catSet = uiApp.Application.Create.NewCategorySet();
    catSet.Insert(cat);

    definition = defGroup.Definitions.Create(defOptions);

    return definition;
}

它返回预期的内容:

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

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

<?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"}} 。 但我看到“url = http%3A%2F%2Flink.cok”已经发布。

1 个答案:

答案 0 :(得分:0)

我需要发送json,但json为“name:value”,而不是默认的“name:name,value:value”。所以我发现:

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

data = JSON.stringify(data);

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