dsvbtgo639708 2014-01-23 20:44 采纳率: 0%
浏览 69
已采纳

通过Ajax发送flash消息(使用cookie好/坏做法?)

I'd like to send a flash message to show when a request finished. I'd like to put the message directly in PHP, because the logic of which flash message should in my opinion be in the PHP.

My problem is that I send Json data, for example when you GET users/

The JS receives:

[{user:"John","connected":true},{user:"Jane","connected":false},...] // =data

I would like to send the flash Message inside the response, but I don't want to change the Json Output (because it becomes less Developper friendly to send a custom object like {"flash_message":"You are connected","data":data})

So I thought about setting some Cookies that expire in 1 minute, so I can show the flash message when the request is received.

Is this good practice ?

  • 写回答

1条回答 默认 最新

  • duanlu6268 2014-01-28 13:40
    关注

    Using cookies is not the best way to go here, because cookies are intended to be persistent data storages, not to send data on a request.

    Custom requests headers are much more appropriated.

    In PHP you can send them like this:

    header("X-flash-message-content: $message");
    

    In JS you can retrieve them like this

    var req = new XMLHttpRequest();
    req.open('GET', document.location, false);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    console.log(headers);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?