How can I send JSON data to server

前端 未结 7 994
旧巷少年郎
旧巷少年郎 2021-01-04 00:25

Well, here is the story:

I have some data need to send to server, but they should turned into JSON dataType first.

I made such ajax call:

            


        
7条回答
  •  一整个雨季
    2021-01-04 01:04

    There are many ways to send JSON data to the server

    1. Using Ajax

    var data = ;
    var url  = '';
    jQuery.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            var jsonObj = jQuery.parseJSON(data);
            alert(jsonObj.encPassword);
        },
        failure: function(errorMsg) {
            alert(errorMsg);
        }
    });
    

    2. Using Curl

    
    

    3. Using Streams

     array(
            'method'  => 'POST',
            'content' => json_encode( $data ),
            'header'=>  "Content-Type: application/json\r\n" .
                        "Accept: application/json\r\n"
          )
    );
    
    $context     = stream_context_create($options);
    $result      = file_get_contents($url, false, $context);
    $response    = json_decode($result);
    var_dump($response);
    

    4. Raw HTTP Post

    Using Zend Framework’s HTTP client: http://framework.zend.com/manual/en/zend.http.client.advanced.html#zend.http.client.raw_post_data

    $json = json_encode($data);
    $client = new Zend_Http_Client($url);
    $client->setRawData($json, 'application/json')->request('POST');
    var_dump($client->request()->getBody());
    

    SOURCE:- https://blog.magepsycho.com/sending-json-data-remote-server/

提交回复
热议问题